当试图填充一个字段时,返回的只是最初为该字段保存的对象
在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
字段。前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'
})