【问题标题】:Mongoose - Subdocument, can not manually populate / set ref fieldMongoose - 子文档,不能手动填充/设置参考字段
【发布时间】:2015-05-21 23:26:26
【问题描述】:

我有一个带有子文档的架构,如下所示:

User: {
  events: [{
    sender: {
      type: Schema.ObjectId,
      ref: 'User'
    }
  }]
}

现在说我检索子子文档并且我已经从数据库中检索了“发件人”,我无法手动设置它,这就是我的意思:

var sender = User.findBy.... // I retrieve the sender
var event = user.events.id(id); // I retrieve the event by ID for the current user

// Now I want to do this but it doesn't work
event.sender = sender; // does not assign, it still remains an ObjectId

我希望以上内容基本上可以自己手动填充,因为 mongoose 似乎不支持填充 single 子文档实例(如果我错了,请纠正我并且有办法)。

我知道它可以填充整个事件数组,但我只需要为一个实例执行此操作,不需要填充数组中的所有事件的开销。

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    对于和我有同样问题的人。现在 mongoose 4.0 支持此功能。

    对于 3.x 或更低版本的用户,实际上并没有合适的替代解决方案,但可以通过将对象转换为纯 JSON 对象来部分实现。

    通过 .toObject().toJSON() 然后进行分配。 但是请注意,您将失去 mongoose 功能,因此只有在纯粹是在返回客户端之前才执行此操作。

    【讨论】:

      【解决方案2】:

      如果您想手动填充它,只需执行以下操作:

      User.findOneById(sender, function(err, foundSender) {
          event.sender = foundSender;
      });
      

      【讨论】:

      • 这就是我所做的,如果你看我上面的例子,它不起作用,猫鼬对象不接受分配。
      猜你喜欢
      • 2020-11-21
      • 2021-02-24
      • 2017-01-27
      • 1970-01-01
      • 2014-08-16
      • 2020-04-18
      • 2015-10-10
      • 1970-01-01
      • 2015-03-04
      相关资源
      最近更新 更多