Mongoose对象模式:如何在mongoosejs中声明模式以便能够迭代选项字段?

时间:2016-11-21 03:27:36

标签: mongodb mongoose-schema

目前mogo通过mongoose的数据如下。一旦我把它从mongo中拉出来,我希望能够迭代选项。 目前,如果我将此记录保存到变量“记录"。我需要做record.options [0] .option1.check,我想避免[0]。 我希望能够迭代一个对象并能够执行以下操作。 record.option1.choice1 record.option2.choice2

my schema is 
    var questionSchema = new mongoose.Schema({
    question: String,
    question_slug: String,
    options: []
});



    {
        "_id" : ObjectId("5832609483bf491db3d8faa1"),
        "question" : “What is the capital of Illinois?",
        "question_slug" : “what-is-the-capital-of-illinois",
        "options" : [
                {
                        "option1" : {
                                "check" : "on",
                                "choice" : “Springfield"
                        },
                        "option2" : {
                                "check" : "",
                                "choice" : “Chicago"
                        }
                }
        ],
        "__v" : 0
} 

1 个答案:

答案 0 :(得分:1)

您无法定义record.option1.choice1record.option2.choice2的架构,因为option1option2似乎是动态的。

但您可以通过[0]而不是record.options[0].option1.checkoptions定义为Object来避免schema array

因此,您可以使用record.optionsrecord.options.option1等迭代对象record.options.option2

var questionSchema = new mongoose.Schema({
    question: String,
    question_slug: String,
    options: {
       type: Object
    }
});



{
    "_id" : ObjectId("5832609483bf491db3d8faa1"),
    "question" : “What is the capital of Illinois?",
    "question_slug" : “what-is-the-capital-of-illinois",
    "options" : {
                    "option1" : {
                            "check" : "on",
                            "choice" : “Springfield"
                    },
                    "option2" : {
                            "check" : "",
                            "choice" : “Chicago"
                    }
    },
    "__v" : 0

}