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);
};
});
})};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With