Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to populate() a mongoose .findOneAndUpdate object

The code below works, it updates a record or creates one if it doesn't exist yet. However, I'd like to combine this findOneAndUpdate() statement with the populate() method in order to populate the "user" of my object. What would be the right way to add the populate("user") statement to this logic?

I tried adding the populate() method after the findOneAndUpdate finishes but that returns an error saying that this method doesn't exist. I'm running the latest version of mongoose.

LoyaltyCard.findOneAndUpdate({ business: businessid}, { $set: newCard, $inc: { stamps: +1 } }, { upsert: true}, function(err, card){

    if(err)
    {

    }
    else
    {

    }

    res.json(result);
});
like image 555
Jorre Avatar asked Jun 03 '14 20:06

Jorre


People also ask

How do I populate in MongoDB?

Mongoose Populate() Method. 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.

What does findOneAndUpdate returns?

As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied.

What is the difference between updateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

What is new true in MongoDB?

If new is true : the modified document if the query returns a match; the inserted document if upsert: true and no document matches the query; otherwise, null .


1 Answers

Use exec() instead of a callback parameter:

LoyaltyCard.findOneAndUpdate(
        {business: businessid},
        {$set: newCard, $inc: {stamps: +1}},
        {upsert: true}
    )
    .populate('user')
    .exec(function(err, card) {
        if (err) {
            // ...
        } else {
            res.json(result);
        }
});
like image 188
Gergo Erdosi Avatar answered Sep 24 '22 05:09

Gergo Erdosi