mongoose to determine update-upsert is doing insert or update

2024/2/27 9:26:17

I want to test if "upsert" option for updating is woking fine. So I "upsert" an object into mongodb twice with same key. However it didn't show inserted message. Was I missing something ?

(mongodb : v2.6.3; mongoose : 3.8.15)

Member.findOneAndRemove({user_id: 1},function (err, doc) {if (!err) onsole.log(doc ? 'deleted' : 'not found');
}); // -> deleted, make sure user_id = 1 doesn't existMember.update({user_id: 1}, {$set: {name: "name1"}}, {upsert: true, new: false}, // new : false, so that I can detect original doc is null then know it's a new one.function (err, doc) {if (!err) {console.log(doc ? 'updated' : 'inserted')}
}); // -> updated ? But it shoule be inserted, right ?Member.update({user_id: 1}, {$set: {name: "name2"}}, {upsert: true, new: false},function (err, doc) {if (!err) {console.log(doc ? 'updated' : 'inserted')}
}); // -> updated, yes, no problem.

Thank you for any hint.

============ answer =============

Use .findOneAndUpdate instead of .update ! Moreover, make sure option is {upsert: true, new: false}, so that the callback's 2nd parameter(doc) could be original document in case.


The .update() method in mongoose takes three arguments to the callback, being err, the numAffected, and a raw response. Use the "raw" object to see what happened:

Member.update({user_id : 1}, {$set : {name:"name1"}}, {upsert : true }, function (err, numAffected, raw) {if (!err) {console.log(raw)}

You'll see a structure like this:

{ ok: true,n: 1,updatedExisting: false,upserted: [ { index: 0, _id: 5456fc7738209001a6b5e1be } ] }

So there is always the n and 'updatedExistingkeys available, where the second is false on upserts and true otherwise.upsertedwill contain the_id` values of any new documents created.

As for n or the "numAffected", this is basically always 1 where a document was matched under the legacy write concern responses.

You can see the new WriteResult response in MongoDB 2.6 and above using the Bulk Operations form:

var bulk = Member.collection.initializeOrderedBulkOp();
bulk.find({user_id : 1}.upsert().update({$set : {name:"name1"}});
bulk.execute(err,result) {console.log( JSON.stringify( result, undefined, 2 ) );

Which on a first iteration you get something like this:

{"ok": 1,"writeErrors": [],"writeConcernErrors": [],"nInserted": 0,"nUpserted": 1,"nMatched": 0,"nModified": 0,"nRemoved": 0,"upserted": [{"index": 0,"_id": "5456fff138209001a6b5e1c0"}]

And a second with the same parameters like this:

{"ok": 1,"writeErrors": [],"writeConcernErrors": [],"nInserted": 0,"nUpserted": 0,"nMatched": 1,"nModified": 0,"nRemoved": 0,"upserted": []

And the document would only be marked as "modified" where something was actually changed.

So at any rate, .update() operations do not return the modified document or the original document. That is the .findOneAndUpdate() method, a mongoose wrapper around the basic .findAndModify() which performs an atomic operation. The .update() methods are typically meant for bulk operations and as such do not return document content.

Related Q&A

Is it permited to download javascript code to iPhone

I have an hybrid application, its basically a website running from the application folder inside a UIWebview. The problem is that I was planning to update my website by downloading the whole website fr…

Read cookie which is created from NewCookie()

I created a cookie using Newcookie() and I can access it thorough the browser as below. Now I need to read the cookiefunction getCookieValue(cookieName) {console.log("=====getCookieValue=======&qu…

JavaScript Add Class When Link is Clicked

I have these links:<a class="active" href="#section1">Link 1</a> <a href="#section2">Link 2</a>When a link 2 is clicked I would like it to receive…

webview dont display javascript

I have a WebView in which i display web content which i have no control over. The content displays fine, but have links which spawn a popup window. The javascript function that does that looks like thi…

How do I find objects with a property inside another object in JavaScript

I have a object with all my users, like so:var users = {user1:{}, user2:{}}, And every user has a isPlaying property. How do I get all users that have isPlaying false?

Bootstrap Carousel Not working

Im trying to implement the Twitter Bootstrap carousel, and so far Ive been unsuccessful. I have the following page:<!DOCTYPE html> <html lang = "en"> <head><meta charset=…

How to override inline css through javascript?

can we override inline css through javascript? with IE6 compatibility.I found this pure css solution but not works in IE.…

JavaScript (ES6): Using spread operator inside conditional expression (?-operator) [duplicate]

This question already has answers here:Spread syntax ES6 with statement(2 answers)Closed 4 years ago.In JavaScript its possible to merge array with another using the ... (spread) operator as follows [.…

initMap is not a function Google Maps Javascript

I know this question has been asked. But I still cant get past it. I am simply trying to get googlemaps API loaded in js fiddle. I cannot get past the error:initMap is not a function. My jsfiddle here:…

Get text (not url) from address bar in Google Chrome

I want to retrieve the text that the user has typed into the currently visible address bar, using Javascript. This is for google chrome only.Is this possible? I know you can get the document URL via w…