【发布时间】:2015-05-15 22:54:54
【问题描述】:
使用 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。 我怎样才能使选择正确显示在数据库中? 如何在数据库中显示结果?
【问题讨论】: