问题描述
首先,哪个最好?findAndModify
或findOneAndUpdate
或findByIdAndUpdate
?
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)
}
我想找到发票的序列号,加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
这是我的模型:
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');
这是我的findkey
nodejs函数....
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);
};
});
})};
推荐答案
猫鼬有findOneAndUpdate
(相当于mongoBD findAndModify .MongoDB还引入了 findOneAndUpdate 在版本> = 3.2中)和findByIdAndUpdate
.这就是findAndModify
无法与猫鼬一起使用的原因.
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.
关于哪个更好,在 findOneAndUpdate 中,您可以传递查询对象包含多个字段,而 findByIdAndUpdate 仅将id作为第一个参数.
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.
这篇关于findAndModify或findOneAndUpdate-“不是函数";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!