I want to use the findOneAndUpdate()
method to either create a document if it doesn't exist, or update it if does exist. Consider the following code:
SampleComment = new Comment({
id: '00000001',
name: 'My Sample Comment',
...
})
This is my attempt to find out if SampleComment
aldready exists, and if so, update it, otherwise creating it:
Comment.findOneAndUpdate(
{ id: SampleComment.id },
{ SampleComment }, // <- NOT PASSING THE OBJECT
{ upsert: true, setDefaultsOnInsert: true },
function(error, result) {
...
});
I'm trying to pass the Model-instance as an object in the second argument, but result is only returning the default values of the model. Same goes for the document itself.
How do I pass the entire object SampleComment
correctly in the second argument?
What's actually happening when you're calling findOneAndUpdate()
with your Document
object as your update object with { SampleComment }
is you're destructuring that to be SampleComment : {...}
.
Mongoose will then go and look at your database document for any property named SampleComment
, find none, and then do nothing. Returning to you a document where nothing would have changed.
What you can do to fix this is convert your Document back to a plain update object first with Mongoose's toObject()
method, remove the _id
(since that property is immutable and you don't want to replace it anyway with an update) and then save it with your existing findOneAndUpdate()
method. eg:
let newComment = SampleComment.toObject();
delete newComment._id;
Comment.findOneAndUpdate(
{ id: SampleComment.id },
newComment,
{ upsert: true, setDefaultsOnInsert: true },
function(error, result) {
...
}
);
You can then see the updated document in your database. To receive the updated document in your result
you need to also pass the option { new: true }
to your options object.
Here's the link to Mongoose's toObject() Document method documentation.
By default the returned result is going to be the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument named new
with the value true
.
Comment.findOneAndUpdate({id: SampleComment.id}, SampleComment, {new: true, upsert: true, setDefaultsOnInsert: true}, function(error, result) {
if(error){
console.log("Something wrong when updating data!");
}
console.log(result);
});
See http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate:
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = 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