猫鼬是否支持Mongodb的findAndModify方法? [英] Does Mongoose support the Mongodb `findAndModify` method?

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

问题描述

我想使用findAndModify通过Mongoose自动增加一个字段.

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

但是,下面的代码将引发错误"TypeError:对象#没有方法'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);

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆