【问题标题】:Mongoose populate followers same document猫鼬填充关注者相同的文档
【发布时间】:2018-02-21 00:34:27
【问题描述】:

我需要从相同的用户模式填充 ObjectId 参数我想要做的是我有“用户”文档,每条记录都有关注者,参考是相同的用户模式。

var userSchema = new Schema({
  username: {type: String, unique: true, trim: true},
  password: {type: String},
  email: {type: String, trim: true},
  avatar: {type: String},
  fullname: {type: String},
  bio: {type: String},
  phone: {type: Number},
  country: {type: String},
  postal: {type: Number},
  followers: [{ type: Schema.ObjectId, ref: 'User' }],
  followed: [{ type: Schema.ObjectId, ref: 'User' }],
  registered: {type: Date, default: Date.now}

});

var User = mongoose.model('users',userSchema);

现在,当我尝试打印用户信息关注者数组时,返回 ObjectId 而不是全部信息

我尝试用这个 sn-p 打印

User.find().exec(function(error, groups) {    
    return res.status(200).send(groups);
  });

【问题讨论】:

  • 请在您尝试检索用户信息的位置显示您的代码
  • @t3__rry 添加到我的问题中
  • 正如@Kxng Kombian 建议的那样,您可以使用Mongoose 的population mongoosejs.com/docs/populate.html#population 但在您的定义中,您需要mongoose.Schema.Types.ObjectId
  • 还是得到[{followers:[5a8c52a9a11412b04b48a933],对象id而不是对象信息

标签: node.js mongodb express mongoose


【解决方案1】:

你想在这里实现的是

User.find({})
.populate('followers')
.populate('followed')
.then(users => {

})

这将填充关注者并跟随他们各自的用户对象

【讨论】:

  • DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程
  • 在你的 mongodb 连接之前添加 mongoose.Promise = global.Promise;
  • 它工作正常,问题是 Ref 不正确我将 Ref: User 更改为 Ref: users
猜你喜欢
  • 2021-02-11
  • 2013-10-05
  • 2021-04-26
  • 2021-10-07
  • 2016-08-17
  • 2017-05-07
  • 2015-07-28
  • 2020-04-30
  • 1970-01-01
相关资源
最近更新 更多