Mongoose query.populate only returns 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字段。前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'
    })

最新更新