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!
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.
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.
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.
You have to add "justOne : true" to your virtual field config :
Order.virtual('client', {
type: 'ObjectId',
ref: 'User',
localField: 'clientId',
foreignField: '_id',
justOne : true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With