【问题标题】:how do I populate a document mongoose or save refs如何填充文档猫鼬或保存参考文献
【发布时间】: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


【解决方案1】:

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

    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

【讨论】:

  • 你不能这样做。您必须将questions 设置为某些东西。 Doc 调用“保存参考”,所以这是我的问题。我不知道该怎么做。
  • 如何在不保存新商店的情况下添加问题并且仍然能够填充它?我所看到的是,当您保存问题时,您会保存商店。我不想那样做。还是不明白。
  • 并且填充需要一个字符串。 TypeError: utils.populate: invalid path. Expected string. Got typeof "function"
猜你喜欢
  • 2014-09-06
  • 2021-02-11
  • 2016-06-10
  • 2023-03-10
  • 2017-09-13
  • 2015-01-13
  • 2019-07-14
  • 1970-01-01
  • 2021-04-26
相关资源
最近更新 更多