Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query.populate only returns objectId

When trying to populate one field all that is returned is the objectid that was originally saved for that field

In 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);

In 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);

I save my gift models by adding the _id for the user to the owner.user field in my gift.

Then when I try to populate the user field during a query only the _id field is returned. 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);
                }
            });
    };
like image 485
Matt Foxx Duncan Avatar asked Dec 22 '25 04:12

Matt Foxx Duncan


1 Answers

The path you want to populate is owner.user, not just user, so you should change this:

return Gift.find()
    .populate({
        path:'user',
        model:'User'
    })

To this:

return Gift.find()
    .populate({
        path:'owner.user',
        model:'User'
    })
like image 55
Sergey K Avatar answered Dec 23 '25 17:12

Sergey K