Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: '[email protected]' } ] }

This is what I want to achieve:

{ _id: 5ad903d90443fe13b8c9061a,
    client: { _id: 5b3755fe69635d1e942d00a8, email: '[email protected]' } }

Thank you for any help or suggestions!

like image 337
Alex Tuhlom Avatar asked Sep 16 '18 11:09

Alex Tuhlom


People also ask

What is virtual populate in mongoose?

Populating Virtuals: In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

How does Mongoose populate?

Example 2: We will perform the query to find all the posts using populate() method. To overcome the above problem, populate() method is used to replace the user ObjectId field with the whole document consisting of all the user data.

What is virtuals in MongoDB?

Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document's collection.


1 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

});
like image 120
FAROUK BLALOU Avatar answered Sep 19 '22 23:09

FAROUK BLALOU