CNode

mongo数据库,自定义id的自增,有方法么

3384324085发布于13 年前最后回复13 年前7 回复6812 浏览0 收藏
查看回复

回复 (7)

B
balascus#1·13 年前

可以通过自己管理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();
	  }
 }); 
B
balascus#6·13 年前

在nosqlfan.com中也有mongodb的专题

I
inosqlorg#7·13 年前
参与回复
登录后即可参与回复。登录