本文介绍了Mongoose 是否支持 Mongodb 的 findAndModify 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 findAndModify 以原子方式递增字段,使用 Mongoose.

I would like to use findAndModify to atomically increment a field, using Mongoose.

然而,下面的代码抛出错误TypeError: Object # has no method 'findAndModify'":

However, the code below throws the error "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!");
     }
});

推荐答案

该功能没有很好地(阅读:根本)文档化,但在阅读源代码后,我想出了以下解决方案.

The feature is not well (read: at all) documented, but after reading through the source code, I came up with the following solution.

创建您的集合架构.

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);

这篇关于Mongoose 是否支持 Mongodb 的 findAndModify 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 02:31