Node.js 在另一个模式中用作数组的mongoose模式
使用express 4.9.0、mongoose 3.8.24和MongoDB 2.6.8 我有两个模式,第一个是提供问题,第二个是提供一些可能的选择和投票的机会 我的问题是这些选择没有进入数据库,因此我无法显示它们 我创建了以下代码:Node.js 在另一个模式中用作数组的mongoose模式,node.js,mongodb,mongoose,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 S
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}]});
new Model()
创建多个文档,它似乎建议您可以为正在创建的新文档向其传递一个值对象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() */
});
你可能会发现这个相关的问题很有用:谢谢你,马可现在有了以下内容:\nchoiceData=[{choice:“red”,vote:0},{choice:“green”,vote:0},{choice:“blue”}];ChoiceModel.create(choiceData,function(){var mgTypes=mongoose.Types,args=arguments;if(args[0])throw err;var question=QuestionModel({question:“你最喜欢哪种颜色?”,选项:[mgTypes.ObjectId(args[1].\id),mgTypes.ObjectId(args[2].\id),mgTypes.ObjectId(args[3].\id)]);问题.save(函数(err){if(err)throw err;});});