JavaScriptだけでWebサイト開発

node.js + Express + mongodb系 + React でサービスを作るメモ

mongooseでauto increment のフィールド定義と動作確認

Express+mongooseで RDBのようなAUTO INCREMENTフィールドを実現する

mongoose-sequence パッケージをインストール

$ npm install --save mongoose-sequence

app.js

var mongoose = require('mongoose'); 
const option = {
  useMongoClient: true,
};
mongoose.Promise = global.Promise;
mongoose.connect(`mongodb://localhost/nexpress`, option); 

// スキーマ定義
var Schema        = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);

var siteSchema = new Schema ({
  site_id: Number,
  name   : String,
  title  : String
});

// site_id フィールドをAutoIncrementする
siteSchema.plugin(AutoIncrement, { inc_field: 'site_id'});
var Site = mongoose.model('Site', siteSchema);

app.get('/', function(req, res ) {
  site = new Site();
  site.name = 'hoge';
  site.title = 'moge';
  site.save();

  res.send('respond with a resource');
});

ブラウザで / にアクセス 10回ほど

db確認

$ mongo
> use nexpress
switched to db nexpress
> db.sites.find();
{ "_id" : ObjectId("5a0c271cb830a7e523d7bedd"), "site_id" : 1, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c272db830a7e523d7bede"), "site_id" : 2, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c2766001be7e530483144"), "site_id" : 3, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c2769001be7e530483145"), "site_id" : 4, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c29584a2a12e5796ffc10"), "site_id" : 5, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c295a4a2a12e5796ffc11"), "site_id" : 6, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c295d4a2a12e5796ffc12"), "site_id" : 7, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c295f4a2a12e5796ffc13"), "site_id" : 8, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c29614a2a12e5796ffc14"), "site_id" : 9, "title" : "moge", "name" : "hoge", "__v" : 0 }
{ "_id" : ObjectId("5a0c29634a2a12e5796ffc15"), "site_id" : 10, "title" : "moge", "name" : "hoge", "__v" : 0 }
>

備考

siteSchema.plugin(AutoIncrement, { inc_field: 'site_id'});

ここで inc_fieldを指定しない場合は _id が AIフィールドになるらしい

©ichi-bit