mongodb - Mongoose 是否支持 Mongodb `findAndModify` 方法

我想使用 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/

相关文章:

ruby-on-rails - Mongoid 查找器不起作用?

mongodb - 如何在 MongoDB 中创建嵌套索引?

mongodb - 如何使用 Robomongo 连接到 MongoDB Atlas?

node.js - 使用 mongoose 在 mongodb 中设置集合的到期时间

python - pymongo 中的快速或批量更新

mongodb - 我控制修补程序上的 Mongo 错误

java - 如何使用 Java mongodb 驱动程序中的 "_id"字段查询文档?

java - 如何通过Java在MongoDB中一次插入多个文档

mongodb - node.js 的 mongoose 中的十进制/ float

mongodb - 如何使用 Meteor Upsert