当尝试填充一个字段时,所有返回的都是最初为该字段保存的 objectid
在 models/gifts.js
var GiftSchema = new Schema({
name: String,
owner: {
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: false
},
nonRegisteredEmail: {
type: String,
required: false
},
nonRegisteredName: {
type: String,
required: false
}
},
description: String,
url: String
}
});
module.exports = mongoose.model('Gift', GiftSchema);
在 models/user.js
var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String
});
module.exports = mongoose.model('User', UserSchema);
我通过将用户的 _id
添加到我的 gift中的
.owner.user
字段来保存我的 gift
模型
然后,当我在查询期间尝试填充 user
字段时,仅返回 _id
字段。 EX 5388bb3a82f0e4003100a6ba
exports.getAll = function (req, res) {
return Gift.find()
.populate({
path:'user',
model:'User'
})
.exec(function(err,gifts){
if(!err)
{
return res.json(gifts);
}
else{
return res.send(err);
}
});
};
最佳答案
您要填充的路径是 owner.user
,而不仅仅是 user
,因此您应该更改此路径:
return Gift.find()
.populate({
path:'user',
model:'User'
})
对此:
return Gift.find()
.populate({
path:'owner.user',
model:'User'
})
关于mongodb - Mongoose query.populate 只返回 objectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960671/