我正在尝试学习MongoDB,但是在使用嵌入式域时遇到了麻烦。我的应用程序有一个问题,可以包含0个许多选项:

class Question {

    ObjectId id
    String text

    List<Option> optionList = []
    static embedded = ['optionList']
}

class Option {
    ObjectId id

    String text
    static belongsTo = [question: Question]
}

现在,当我要发出一个保存问题的请求时,需要使用以下两个选项:
void testSave() {
    QuestionController questionController = new QuestionController()
    questionController.request.parameters =
        [
                "text": "test question",
                "optionList[0].text": "a",
                "optionList[1].text": "b"
        ]
    questionController.save()
}

这将引发异常:
Invalid property 'optionList[0]' of bean class [groovy.lojzatran.anketa.Question]: Index of out of bounds in property path 'optionList[0]'; nested exception is java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
org.springframework.beans.InvalidPropertyException: Invalid property 'optionList[0]' of bean class [groovy.lojzatran.anketa.Question]: Index of out of bounds in property path 'optionList[0]'; nested exception is java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

当我使用静态hasMany将关系更改为一对多时,它运行良好。

有人可以帮助我吗?

谢谢

最佳答案

替换此行:

List<Option> optionList = []


List<Option> optionList =  new org.springframework.util.AutoPopulatingList<Option>(Option)

10-07 13:27