LoginSignup
6
6

More than 5 years have passed since last update.

Mongooseでインクリメントを実装する

Last updated at Posted at 2016-05-26

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はモンゴーズじゃなくて、マングースです。はい。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6