7 回复
可以通过自己管理ID的序列,例如使用Monogoose:
var Schema = mongoose.Schema;
var models = {};
/**
* 存储ID的序列值
*/
Sequence = new Schema({
_id: String,
next: Number
});
Sequence.statics.findAndModify = function (query, sort, doc, options, callback) {
return this.collection.findAndModify(query, sort, doc, options, callback);
};
Sequence.statics.increment = function (schemaName, callback) {
return this.collection.findAndModify({ _id: schemaName }, [],
{ $inc: { next: 1 } }, {"new":true, upsert:true}, callback);
};
models.Sequence = mongoose.model('Sequence', Sequence);
SomeDoc = new Schema({
'id' : { type : Number, index: { unique: true } },
.........
});
//在创建文档时,获取自增ID值
SomeDoc.pre('save', function(next) {
var that = this;
if( that.isNew ) {
models.Sequence.increment('SomeDoc',function (err, result) {
if (err)
throw err;
that.id = result.next;
next();
});
} else {
next();
}
});