findAndModify or findOneAndUpdate - "is not a function"

Viewed 18808

First of all, which one is best? findAndModify or findOneAndUpdate or findByIdAndUpdate?

In my case I got a table like this:

seqkeys

{ 
    "_id" : "invoice", 
    "seq" : NumberInt(1)
},
{ 
    "_id" : "receipt", 
    "seq" : NumberInt(1)
}

And I want to find the seq number for invoice, add 1 and save. (and then use that number to save the real invoice record in the invoice table)

But I cant get this to work, I constantly get

TypeError: seqkeysTable.findAndModify is not a function

So here is my model:

var mongoose      = require('mongoose');
var Schema        = mongoose.Schema;
var seqkeysSchema = new Schema({
    _id:                String,     // Table Name
    seq:                Number      // Sequence Number
});
module.exports = mongoose.model('seqkeysModel', seqkeysSchema,'seqkeys');

And here is my findkey nodejs function....

var seqkeysModel = require('../../models/seqkeysModel');
var seqkeysTable = mongoose.model('seqkeysModel');
var findKey = function(tableName) {
    return new Promise((resolve, reject) => {
    seqkeysTable.findAndModify(
        { "_id": tableName },
        { $inc: {"seq":1} },
        { new: true }
    ,function (err, data) {
        if (err) {
            reject(new Error('findKey ERROR : ' + err));
            return;
        } else {
            resolve(data.seq);
        };
    });
})};    
2 Answers

findAndModify is a function of MongoBD, That's why that doesn't work with Mongoose.

Both findOneAndUpdate and findByIdAndUpdate works well with Mongoose, perhaps if you wish to use _id to search in the database then go for findByIdAndUpdate else if you are using a different field to search in the database then use findOneAndUpdate.

However, if you try to use findAndModify in MongoDB, you might get the following warning :

DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.

To eliminate this use the following in your code :

mongoose.set('useFindAndModify', false);

Just in case, difference between findByIdAndUpdate & findOneAndUpdate :

findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...)

Related