mongoose模式在另一个模式中用作数组

时间:2015-03-13 12:43:42

标签: node.js mongodb mongoose

使用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。 我怎样才能使数据库中的选择正确显示? 如何在数据库中显示结果?

1 个答案:

答案 0 :(得分:0)

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

var choices = new ChoiceModel({choices: [{choice: "red", vote: 0}, 
                              {choice: "green", vote: 0}, 
                              {choice: "blue", vote: 0}]});
  1. 它似乎与您设置Choices Schema的方式不相符
  2. 我不确定mongoose的API是否允许您使用new Model()创建多个文档mongoose API for Model似乎建议您可以为您正在创建的新文档传递单个值对象
  3. 如果您想一次创建多个文档,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