我想使用 findAndModify 原子地增加一个字段,使用 Mongoose。
但是,下面的代码会抛出错误“TypeError: Object # has no method 'findAndModify'”:
// defining schema for the "counters" table
var tableSchema = new Schema({
_id: String,
next: Number
});
// creating table object for the counters table
var counters_table = mongoose.model('counters', tableSchema);
var tableObj = new counters_table();
// increment the "next" field on the table object
var query = {_id: 'messagetransaction'};
var update = {'$inc': {next: 1}};
var ret = tableObj.findAndModify(query, [], update, true, true, function(err) {
if (err) {
throw err;
}
else {
console.log("updated!");
}
});
最佳答案
该功能没有很好的记录(阅读:根本),但在阅读了源代码后,我想出了以下解决方案。
创建您的集合架构。
var Counters = new Schema({
_id: String,
next: Number
});
在架构上创建一个静态方法,该方法将公开模型集合的 findAndModify 方法。
Counters.statics.findAndModify = function (query, sort, doc, options, callback) {
return this.collection.findAndModify(query, sort, doc, options, callback);
};
创建您的模型。
var Counter = mongoose.model('counters', Counters);
查找和修改!
Counter.findAndModify({ _id: 'messagetransaction' }, [], { $inc: { next: 1 } }, {}, function (err, counter) {
if (err) throw err;
console.log('updated, counter is ' + counter.next);
});
奖金
Counters.statics.increment = function (counter, callback) {
return this.collection.findAndModify({ _id: counter }, [], { $inc: { next: 1 } }, callback);
};
Counter.increment('messagetransaction', callback);
关于mongodb - Mongoose 是否支持 Mongodb `findAndModify` 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7334390/