Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findAndModify or findOneAndUpdate - "is not a function"

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);
        };
    });
})};    
like image 303
torbenrudgaard Avatar asked Nov 29 '22 22:11

torbenrudgaard


1 Answers

Mongoose has findOneAndUpdate (equivalent of mongoBD findAndModify. MongoDB also introduced findOneAndUpdate in version >= 3.2) and findByIdAndUpdate. That's why findAndModify won't work with Mongoose.

As to which one is better, in findOneAndUpdate you can pass query object containing multiple fields while findByIdAndUpdate only takes id as the first parameter.

like image 196
Talha Awan Avatar answered Dec 01 '22 11:12

Talha Awan