VRK VRK - 1 year ago 66
Node.js Question

Mongoose get collection data if present the update otherwise insert

I am new to mongodb and mongoose with ExpressJS. It may be simple question but I dont success.

var BookCounter = new Schema({
counter: {type: Number,},
book: {type: String, min: 18}

this is the my schema and the following is the my question:

I want to check that xyz book is present or not

if book is present

Then I have to update the book counter by one.


I have to insert new book.

Can you please help me ..

Thanks in advance :)

Answer Source

You need an update operation findOneAndUpdate() that uses the options upsert to create the document if it does not exist and the new option if set to true returns the newly created/modified document rather than the original, alongside the $set and $inc field update operators.

The following example demonstrates this:

var query = { "book": "xyz" },
    update = { "$inc": { "counter": 1 } },
    options = { "upsert": true, "new": true };

// Find the document
Book.findOneAndUpdate(query, update, options, function(err, result) {
    if (err) handleError(err);    
    else {
        // do something with the document
        console.log(JSON.stringify(result, null, 4));