【问题标题】:Mongoose / Mongodb - should I explicitly add objectid to populate?Mongoose / Mongodb - 我应该明确添加 objectid 来填充吗?
【发布时间】:2020-09-26 17:37:05
【问题描述】:

所以我有两个模型,一个是users,另一个是sessions

最初设置为:

const users = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    username: {type: String, unique: true},
}
);
module.exports = mongoose.model('User', users,);

然后我继续添加另一个模型,称为会话,

const sessions = mongoose.Schema({
    _id: {type: mongoose.Schema.Types.ObjectId, default: mongoose.Schema.Types.ObjectId, null: false},
    user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    timestamp: {type: Date},
});

module.exports = mongoose.model('Sessions', sessions);

然后我决定,我希望能够与用户一起拉用户的会话并添加 sessions: [{type: mongoose.Schema.Types.ObjectId, ref: 'SurfSessions', default: null}] 我的用户模型架构。

我很快了解到users.findOne(username:admin).populate('sessions') 本身不会填满会话,因为sessions 返回一个空数组[]

由于我在 users 中没有填充 objectidsessions,这是否意味着我无法填充 sessions 或者还有其他方法吗?

【问题讨论】:

  • 请查看this有类似问题的帖子
  • 谢谢,这个问题之前已经回答过很多次了,但还是没有回答我的问题。

标签: node.js mongodb express mongoose


【解决方案1】:

您应该能够使用虚拟填充来做到这一点:

const users = new mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    username: { type: String, unique: true },
  },
  { toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
module.exports = mongoose.model('User', users);

然后:

userSchema.virtual('sessions', {
  ref: 'Session', // model to search in
  foreignField: 'user_id', 
  localField: '_id', // checks where user_id on session === _id on user
});

在此之后,正常使用 .populate('sessions') 。有关更多信息,请查看:https://mongoosejs.com/docs/tutorials/virtuals.html#populate

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 2021-03-03
    • 2017-04-20
    • 2021-03-19
    • 2021-08-25
    • 1970-01-01
    • 2020-10-14
    • 2017-11-05
    • 2016-05-15
    相关资源
    最近更新 更多