Mongoose – Create document if not exists, otherwise, update- return document in either case

You are looking for the new option parameter. The new option returns the newly created document(if a new document is created). Use it like this:

var query = {},
    update = { expire: new Date() },
    options = { upsert: true, new: true, setDefaultsOnInsert: true };

// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
    if (error) return;

    // do something with the document
});

Since upsert creates a document if not finds a document, you don’t need to create another one manually.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)