猫鼬模式用作另一个模式中的数组

mongoose schema used as an array in another schema

使用 express 4.9.0、mongoose 3.8.24 和 MongoDB 2.6.8

我有两个模式,第一个是提供问题,第二个模式是提供一些可能的选择和对最喜欢的答案进行投票的机会。

我的问题是选择没有进入数据库,因此我无法显示它们。

我创建了以下代码:

var Schema = mongoose.Schema;

var ChoiceSchema = new Schema({
    choice: String,
    vote: Number
});

var QuestionSchema = new Schema({
    question: String,
    choices: [{type: Schema.ObjectId, ref: 'Choices'}],
    pub_date: {
        type: Date,
        default: Date.now
    }
});
var QuestionModel = mongoose.model('question', QuestionSchema);
var ChoiceModel = mongoose.model('Choices', ChoiceSchema);
mongoose.connect('mongodb://localhost/polls');

var question = new QuestionModel({
    question: "Which colour do you like best?"
});
question.save(function(err){
    if(err) throw err;
    var choices = new ChoiceModel({choices: [{choice: "red", vote: 0}, 
                                {choice: "green", vote: 0}, 
                                {choice: "blue", vote: 0}]});
    choices.save(function(err) {
        if (err) throw err;
    });
});

在页面下方,我尝试获取结果,但选择不会进入 mongodb 数据库。

app.get('/choice', function(req, res) {
    QuestionModel
    .findOne({ question: "Which colour do you like best?"})
    .populate('choices')
    .exec(function(err, question){
        if (err) throw err;
        // need some code here to display the answers not sure what to put
    });
    res.send("Hello World"); // This is just to stop express from hanging
});

如果我从命令行检查 MongoDB,我有两个集合。 选择、问题

> db.choices.find().pretty()
{ "_id" : ObjectId("5502d6612c682ed217b62092"), "__v" : 0 }

> db.questions.find().pretty()
{
    "_id" : ObjectId("5502d6612c682ed217b62091"),
    "question" : "Which colour do you like best?",
    "pub_date" : ISODate("2015-03-13T12:21:53.564Z"),
    "choices" : [ ],
    "__v" : 0
}

正如您在上面看到的那样,选项应该有红色、绿色和蓝色三种颜色,每种颜色的投票设置为 0。 我怎样才能使选择在数据库中正确显示? 如何在数据库中显示结果?

我想知道这个问题是否与您尝试将选项添加到他们的集合中的方式有​​关:

var choices = new ChoiceModel({choices: [{choice: "red", vote: 0}, 
                              {choice: "green", vote: 0}, 
                              {choice: "blue", vote: 0}]});
  1. 它似乎与您设置选择架构的方式不符
  2. 我不确定 mongoose 的 API 是否允许您使用 new Model() 创建多个文档 mongoose API for Model 似乎建议您可以将单个值对象传递给它您正在创建新文档。

如果您想一次创建多个文档,Mongoose's Model#create 可能就是您要找的:

var choices = [{choice: "red", vote: 0}, 
               {choice: "green", vote: 0}, 
               {choice: "blue", vote: 0}];
ChoiceModel.create(choices, function (err, jellybean, snickers) {
    if (err) // ...
    /* your choices have been stored to DB. No need to call .save() */
});

您可能会发现这个相关问题很有用:Mongoose create multiple documents