Why does mongoose populate virtual field as array instead of single item?

Viewed 1827

I want to populate an object into a virtual field with mongoose as a JSON object, but it always returns an array with a single item.

Here is my scheme code (part with virtual field):

Order.virtual('client', {
    type: 'ObjectId',
    ref: 'User',
    localField: 'clientId',
    foreignField: '_id'
});

Here is how I do population:

Order.findOneAndUpdate({ internalStatus: 2}, { internalStatus: 3 })
    .lean()
    .populate({ path: 'client', select: 'email' })
    .exec(function (err, order) {
        //...
    });

Here is what I receive in returned JSON:

{ _id: 5ad903d90443fe13b8c9061a,
    client: [ { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } ] }

This is what I want to achieve:

{ _id: 5ad903d90443fe13b8c9061a,
    client: { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } }

Thank you for any help or suggestions!

2 Answers

You have to add "justOne : true" to your virtual field config :

Order.virtual('client', {
    type: 'ObjectId',
    ref: 'User',
    localField: 'clientId',
    foreignField: '_id',
    justOne : true

});

In mongoose mongoose@5.0.17 I am seeing they return as JSON_OBJECT but when I upgraded to mongoose@5.3.0 , it started retuning as JSON_ARRAY

Related