When running this query:
const project = await models.Projects
.updateOne(
{ _id: projectId },
{
$addToSet:
{
membersIds:
{
$each: membersIds
},
},
},
);
The response I get is the follwoing:
{ n: 1, nModified: 1, ok: 1 }
Is it possible to get an updated object instead of this mongoose data?
UpdateOne returns a mongoose object and not document.
findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).
May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.
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 .
From the docs: [callback] «Function» params are (error, writeOpResult)
which means that there's no way to return a document with updateOne
method.
Instead of updateOne
it's however possible to use findByIdAndUpdate providing lean: true
option
ATTENTION !
I saw the responses, they are all right, BUT, pay attention to add the new option and to set it as true into the query to get the new updated document, otherwise it will return back the document before updating:
models.Projects.findByIdAndUpdate(
{ "_id": projectId },
{ $addToSet:{ membersIds: { $each: membersIds }}})
.exec()
.then((response) => {
console.log('document before updating =>', response);
});
models.Projects.findByIdAndUpdate(
{ "_id": projectId },
{ $addToSet:{ membersIds: { $each: membersIds }}},
{new: true})
.exec()
.then((response) => {
console.log('document after updating =>', response);
});
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