【Node】mongoose-auto-incrementの使用

mongoで連番を使うmodule

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var autoIncrement = require("mongoose-auto-increment");

var db = mongoose.connect("mongodb://localhost/testdb", function(err){
	if(err){console.log(err);}
});
autoIncrement.initialize(db);

var testSchema = new Schema({
	author: { type: Schema.Types.ObjectId, ref: 'Author' },
	name: String,
	date: Date
});
testSchema.pre("save", function(next){
	this.date = new Date();
	next();
});

testSchema.plugin(autoIncrement.plugin, 'Test');
var Test = mongoose.model("Test", testSchema);;

だいたいこんな感じに。 _idの上位4バイトがTimeStampになっているらしいけど使わないので。

{ "_id" : 0, "date" : ISODate("2014-07-08T08:31:11.509Z"), "id" : "hoge",   "_id" : ObjectId("53bbac4f3a506a3f170c5475"), "__v" : 0 }
広告