【发布时间】:2016-09-23 20:21:51
【问题描述】:
我有一个问题集合,我有一个商店模型。我希望 Store 模型中的 questions 字段成为问题集合中的对象 ID 数组。所以我可以稍后使用填充。当我以后做 app.get 时,它应该向我展示一个包含商店信息和所有问题的文档。
var Schema = mongoose.Schema;
var storeSchema = Schema({
name : {type : String},
industry : {type : String},
questions :[{type : Schema.Types.ObjectId, ref : "Questions" }]
})
var questionsSchema = Schema({
question : {type :String}
})
var store = mongoose.model("Store", storeSchema);
var questions = mongoose.model("Questions", questionsSchema)
// questions.create({question: "question2"}, function(err,q){
// console.log("create: " , q)
// })
//something like this
questions.find({}, function(err, doc){
store.create({name : "store 1", industry : "industry 1" , questions : /*get the _ids from the question collection*/ {$push : doc.question}})
})
> db.questions.find().pretty()
{
"_id" : ObjectId("574534a289763c004643fa08"),
"question" : "question1",
"__v" : 0
}
{
"_id" : ObjectId("574534acc90f3f2c0c3d529b"),
"question" : "question2",
"__v" : 0
}
>
【问题讨论】:
-
@jack_blank 你找到解决方案了吗?
标签: node.js mongodb mongoose mongoose-populate