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);
});
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.
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.
findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).
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 .
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);
}
});
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