我想使用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!");
}
});发布于 2011-09-29 13:17:55
这个特性没有很好的文档记录,但在阅读了源代码之后,我想出了以下解决方案。
创建您的集合架构。
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);
});Bonus
Counters.statics.increment = function (counter, callback) {
return this.collection.findAndModify({ _id: counter }, [], { $inc: { next: 1 } }, callback);
};
Counter.increment('messagetransaction', callback);发布于 2013-03-15 23:01:15
现在Mongoose 3.x完全支持这一点,尽管名称略有不同。
http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
http://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove
http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove
发布于 2012-10-23 00:32:33
为Mongoose 3.x增加了工作版本
var mongoose = require('mongoose');
var CounterSchema = new mongoose.Schema({
_id: String,
next: {type: Number, default: 1}
});
CounterSchema.statics.increment = function (counter, callback) {
return this.findByIdAndUpdate(counter, { $inc: { next: 1 } }, {new: true, upsert: true, select: {next: 1}}, callback);
};使用类似如下的内容:
Counter.increment('photo', function (err, result) {
if (err) {
console.error('Counter on photo save error: ' + err); return;
}
photo.cid = result.next;
photo.save();
});我希望有人能派上用场
https://stackoverflow.com/questions/7334390
复制相似问题