mongooseでインクリメントてきなやつを実装したいと思った。
ググッて海外のドキュメントやらみながら実装した。
モデルでインクリメントを実装する
例えば以下のような、モデルを定義するとする。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var hogeSchema = new Schema({
id: {
type: Number,
required: true,
unique: true
},
count: {
type: Number,
required: true
}
});
var Hoge = mongoose.model('Hoge', hogeSchema);
module.exports = Hoge;
count
をインクリメントしたい。
スキーマを定義しているすぐ下に、以下のようなメソッドを実装する。
hogeSchema.statics.increment = function(id, done) {
return this.collection.findOneAndUpdate({
id: id,
}, {
$inc: { count: 1 }
}, {
new: true,
upsert: false
}, function(err, data) {
done(null, data);
});
}
$inc
ってのがMongoDBの標準の機能であるっぽく、それで1ずつ増やすみたいなことをしてるっぽい。
コントローラーから呼び出す
コントローラーとかからhoge
モデルのincrementを呼び出すとcount
を+1することができる。
var db = require('イイ感じにモデルを読み込む');
db.hoges
.increment('+1したいドキュメントのidを渡す', function(err, result) {
console.log(result);
});
めでたい
mongooseはモンゴーズじゃなくて、マングースです。はい。