Using upsert to Insert Documents in a Collection

Normal updates do not automatically insert objects because they incur a cost when they need to determine whether an object exists. If you know that an object exists, then a normal update() is efficient; insert() is better if you know that a document does not already exist. When you want a combination of updating an object if it exists and inserting it if it does not, you use upsert.

To implement upsert, you include the upsert:true option in the update() method’s options parameter. This tells the request to try to update the object if it exists and to insert the object specified if it doesn’t already exist.

Listing 14.6 shows how to use upsert with the update() method. The update() in lines 9–12 ...

Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.