Shehzad Lokhandwalla Shehzad Lokhandwalla - 5 months ago 34
Node.js Question

NodeJS MongoDb find duplicate values and Modify increment

I have a collection called books that has objects-- isbn, author, number of books

(num)
, publisher and so on.
Just after I get the book information from my view, I want to check if the isbn of the book already exists and if so I want t increment the number of books. However, the number never increments even if its the same book. Anyone knows why?

var collection = db.collection('books');

var item=collection.findAndModify({
query: { isbn: req.body.isbn13 },
update: { $inc: { num: 1 } },
});
if(item==null)
{add the info to the database}

Answer

You should be using a callback function to check if the item is null or not found,

https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

var collection = db.collection('books');

        var item=collection.findAndModify({
        query: { isbn: req.body.isbn13 },
        update: { $inc: { num: 1 } },
        }, function(err, object) 
{
//check here & add the info to the database
});