6

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!

Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
Alex Tuhlom
  • 61
  • 2
  • 5

2 Answers2

15

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

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

});
FAROUK BLALOU
  • 698
  • 1
  • 10
  • 19
0

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

Raghu Vallikkat
  • 365
  • 5
  • 16