如何填充文件mongoose或保存refs

时间:2016-05-26 02:25:11

标签: node.js mongodb mongoose mongoose-populate

我有一个问题集,我有一个商店模型。我希望Store模型中的问题字段是来自问题集合的对象ID数组。所以我以后可以使用populate。当我将来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
}
>

1 个答案:

答案 0 :(得分:0)

填充是使用其他集合中的文档自动替换文档中指定路径的过程。我们可以填充单个文档,多个文档,普通对象,多个普通对象或从查询返回的所有对象。

    var question = new Questions();
    question.save(function(err) {
        var store = new Store({
            name:'sample',
            industry:'tech',
            questions: [question._id],
        });
        store.save(function(err){
         //do whatever you would like, post creation of store.
        });
    });

   Store.find(...).exec(function(err, stores) {
     Questions.populate(stores, function(err, storesPostPopulate) {
      // Now you have Stores populated with all the questions.
     })
   });

由于问题架构中的问题字段是一个数组,因此您始终可以向其推送另一个问题ID。

See mongoose populate

See mongoose Model populate