node.js - Mongoose 无法将 ref -Schema.Types.ObjectId- 设置为其他文档

标签 node.js mongodb mongoose

我正在尝试根据文档 http://mongoosejs.com/docs/populate.html 用 Mongoose 保存文档 首先,我调用parent.save,并在parent.save的回调中使用child.save。 但是当我检查parent.childs时,我可以看到没有添加任何 child 。 父架构是 Home :

var HomeSchema  = new Schema({


    password : String,
    draft :   { type: Boolean, default: true },
    edited :   { type: Boolean, default: false },
    guests : [{type : Schema.Types.ObjectId, ref : 'Guest'}],

    _event : {type : Schema.Types.ObjectId, ref : 'Event'}

});

子架构是 Guest :

var GuestSchema = new Schema({

    _home : {type : Schema.Types.ObjectId, ref : 'Home'},
    firstname : String,
    lastname : String,
    coming : { type: String, default: 'dnk-coming' },
    phone : String,
    email : String,
    address : String,
    edited :   { type: Boolean, default: false },
    draft :  { type: Boolean, default: true }

});

为了避免任何误解,您必须知道这两个架构包含在我的用户架构中:

var userSchema = mongoose.Schema({
    homes:[homeSchema.HomeSchema],
    events:[eventSchema.EventSchema],
    guests:[eventSchema.guestSchema],

});

现在您应该拥有完全理解执行所需的所有信息:

  UserModel.findById(user._id, function(err, userFound) {
    if (!err) {
      /* cleaning draft*/
      userFound.homes = that.clean(userFound.homes);
      /* setting draft */
      var HomeModel = mongoose.model("Home");
      var homeModel = new HomeModel();
      homeModel.draft = true;


      if (userFound.homes === null) {
        userFound.homes = [];
      }

      homeModel.save(function(err) {
        if (!err) {
          var GuestModel = mongoose.model("Guest");
          var guestModel = new GuestModel();
          guestModel._home = homeModel._id;

          guestModel.save(function(err) {
            if (!err) {
                // @ma08 : According to the doc this line should'nt be required
                //homeModel.guests.push(guestModel._id);  so when I use this obviously the id is correctly set but when I try a populate after saving the populate do not work 
              userFound.homes.push(homeModel);
              userFound.guests.push(guestModel);
              userFound.save(function(err) {
                if (!err) {
                  successCallback();
                }
                else {
                  errorCallback();
                }
              });
            }
          });
        }
      });

此处理不会导致任何错误。但当我对 user.guests 进行字符串化时,它并没有按预期工作:

guests: 
   [ { coming: 'dnk-coming',
       edited: false,
       draft: true,
       _id: 53dcda201fc247c736d87a95,
       _home: 53dce0f42d5c1a013da0ca71,
       __v: 0 }]

这绝对没问题,我得到了 _home id 等...... 然后我对 user.homes 进行字符串化,得到:

  homes: 
   [ { draft: true,
       edited: false,
       guests: [],
       _id: 53dce0f42d5c1a013da0ca71,
       __v: 0 } ]

根据文档,应该设置 guest ,但这不是<--这是我的问题。请帮助我弄清楚我做错了什么。我可以手动设置它,但根据文档,我认为它不应该以这种方式工作。

最佳答案

guestModel.save(function(err) {...

这是错误的,因为您将访客嵌入到 userSchema 中。 因此,跳过 guestModel.save 并只需在 userFound

push guestModel

嵌入文档永远不能作为引用。如果没有获取父文档,则无法指向它。因此,您无法同时进行嵌入和保留对嵌入文档的引用。您应该选择嵌入或添加引用。

我的建议是像这样设计您的架构。将 guest 存储在单独的集合中。将引用存储到 userhome 架构中的 guest。如果您想存储一些关系数据,您可以与引用一起存储,例如 [{guestId:{type:Schema.Types.ObjectId,ref:'Guest'},field1:{type:...},field2:{...}..] ,如果您只需要引用 [{type:Schema.Types.ObjectId,ref:'Guest'}]

关于node.js - Mongoose 无法将 ref -Schema.Types.ObjectId- 设置为其他文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25095461/

相关文章:

node.js - Mongoose - 保存字符串数组

node.js - 如何通过 Sailsjs 使用参数过滤数据库对象

node.js - 当返回 promise 而不是流时,Gulp 结束得太早

node.js - 根据条件使用来自不同集合的 $lookup

node.js - 未处理的拒绝错误: Content-Type header [] is not supported

node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合

javascript - 为什么setInterval不等待指定时间?

javascript - MongoDB - MongoError : connect ECONNREFUSED

Mongodb 列出以前的查询

mongodb - 如何比较mongodb对象数组中不同对象的属性