Mongoose 通过参考搜索自动填充数据
Posted
技术标签:
【中文标题】Mongoose 通过参考搜索自动填充数据【英文标题】:Mongoose auto fill data by searching in reference 【发布时间】:2020-05-08 02:25:17 【问题描述】:const UserSchema = new Schema(
referrals:
ref: 'User',
type: [mongoose.Schema.Types.ObjectId],
,
referredBy:
ref: 'User',
type: mongoose.Schema.Types.ObjectId,
,
);
我希望 Mongoose 在 referredBy
参考中找到当前用户 _id 的用户。
换句话说,例如:找到所有在其referredBy
字段中具有'_IDOfSpecificUser'
的用户,并将所有找到的用户放入referrals
的数组中,其中用户的_id为'_IDOfSpecificUser'
。
如何在猫鼬中处理这个问题?
【问题讨论】:
【参考方案1】:最简单的是使用find
User.
find( "referredBy" : "xxxxxxxxxxxx" ).
exec(function (err, users)
if (err) return handleError(err);
console.log('The users are an array: ', users);
);
参考https://mongoosejs.com/docs/populate.html
如果要将波纹管函数转换为UserSchema中的静态方法,请参考https://mongoosejs.com/docs/api.html#schema_Schema-static和https://mongoosejs.com/docs/2.7.x/docs/methods-statics.html
【讨论】:
以上是关于Mongoose 通过参考搜索自动填充数据的主要内容,如果未能解决你的问题,请参考以下文章
MongoDB和Mongoose:无法使用.populate()填充用户的帖子