LoginSignup
13
8

More than 5 years have passed since last update.

MongoDB (mongoose) で連番をつける

Last updated at Posted at 2014-05-22

MongoDB には連番のユニークな ID をつける仕組みがありません。
なので自分で実装する必要があります。

以下は User スキーマに連番で id をつける例です。(mongoose 3.8.8以降)

models.coffee
# モジュールいろいろ
mongoose = require 'mongoose'
Schema   = mongoose.Schema
ObjectId = mongoose.Schema.ObjectId


###
  シーケンス
###
SequenceSchema = new Schema
  name: { type: String }
  seq:  { type: Number }
SequenceSchema.index { name: 1 }
Sequence = db.model('Sequence', SequenceSchema)


###
  ユーザスキーマ
###
UserSchema = new Schema
  id:   { type: Number, unique: true }
  name: { type: String }

# Middleware  ここがポイント!
UserSchema.pre 'save', (next)->

  return next() unless @isNew

  conditions = name: model.collection.name
  update     = $inc: { seq: 1 }
  options    = upsert: true
  Sequence.findOneAndUpdate conditions, update, options, (err, data)=>
    if !err and data
      @id = data.seq
      next()
    else
      next(err || data)

このように Middleware (Pre) をセットしておくと、

app.coffee
user = new User name: 'nariyu'
user.save()

とするだけで、連番で id が付きます。

こちらからは以上です。

13
8
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
13
8