Node.js Mongoose将引用填充到自己的模式
我有一个猫鼬模式Node.js Mongoose将引用填充到自己的模式,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个猫鼬模式User和一个字段friends,再次引用User模式,如下所示: var UserSchema = new Schema({ name: String, email: { type: String, lowercase: true }, role: { type: String, default: 'user' }, friends: [{ type: Schema.Types.ObjectId, ref: 'User'}] }); var
User
和一个字段friends
,再次引用User
模式,如下所示:
var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
friends: [{ type: Schema.Types.ObjectId, ref: 'User'}]
});
var test = new User({...});
var admin = new User({...});
var users = [test, admin];
User.find({}).remove(function () {
User.create(users, function () {
console.log('finished populating users');
});
});
这很好,我可以在如下设置一些用户ID后在数据库中看到它们:
var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
friends: [{ type: Schema.Types.ObjectId, ref: 'User'}]
});
var test = new User({...});
var admin = new User({...});
var users = [test, admin];
User.find({}).remove(function () {
User.create(users, function () {
console.log('finished populating users');
});
});
但是现在我想在获得单个用户时填充朋友
字段,就像文档中一样,我这样做:
exports.show = function (req, res, next) {
var userId = req.params.id;
User.findById(userId)
.populate('friends')
.exec(function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
res.json(user.profile);
});
};
但是我刚刚得到了正常/未填充的用户ID
我感觉这是因为用户模式的自引用,但ID在数据库中显示良好
建议的副本并没有真正帮助我,因为我甚至没有使用太多的嵌套,问题可能只是模式的自引用
有什么想法吗?提前谢谢
User.findById(userId)
.populate('friends', ['name', 'email'])
.exec(function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
res.json(user.profile);
});
尝试仅使用必填字段(不包括“friends”字段)填充friends,以避免模式的自引用。好的,我找到了问题所在。
user.profile
是来自Mongoose的虚拟模式。因此,我扩展了:
UserSchema
.virtual('profile')
.get(function() {
return {
'_id': this._id,
'name': this.name,
'role': this.role,
'friends': this.friends
};
});
现在,
朋友的填充起作用了 可能是重复的,嗯,可能是,但我没有超过这一个级别。只是populate()。我猜它也试图填充“朋友”的“朋友”?让我知道这是否有效…n如果有效,请接受/投票给我的ans。终于有时间测试了,但仍然不起作用…:-/嘿,我知道了。请看下面我的答案!