[Mongoose E11000 duplicate key error index:] google了很久也没解决,求助。
发布于 10 年前 作者 jie414341055 27622 次浏览 最后一次编辑是 8 年前

mongoose中save函数我的理解是如果存在则更新,否则插入。但是现在显示_id冲突,无法解决。

Schema如下:

var UserSchema = new Schema({
	username: { type: String },
	nickname: { type: String },
    	password: { type: String },
    	email: { type: String },
    	access: { type: Number, default: 0},
}, { collection: 'User' });
mongoose.model('User', UserSchema);

然后在一个更新操作中每次find, modify, save,save过程会报错

{ [MongoError: E11000 duplicate key error index: test.User.$_id_  dup key: { : ObjectId('5362235c895105241d43c46e') }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: test.User.$_id_  dup key: { : ObjectId(\'5362235c895105241d43c46e\') }',
  code: 11000,
  n: 0,
  connectionId: 1,
  ok: 1 }

更新的代码是:

	User.getByName({ username: _currentUser.username }, proxy.done(function(user) {
		if (req.body['email']) user.email = req.body['email'];
		user.save(function(err) {
			if (err) {
				console.log(err);  //这里打印的就是上边的错误
			}
		});
		proxy.emit('save');
	}));

请问是什么问题造成的,我把collection remove掉还是不行。

7 回复

实在是太诡异了,只有_id一个索引,默认建立的,save又不是insert为什么会duplicate呢!

求高人指点迷津啊,折腾一晚上了还是不知道哪里出了问题。

应该是你的proxy里有什么处理将此次save当成insert了 你对save的理解不太对,可以看一下mongoose的代码。

同上,先把proxy拆掉看还报错不

我也是这样的,save之前必须删掉_id很烦躁。

你用的mongoose是什么版本的? 我这边mongoose@3.8.8 测试没有问题, 对应的Model.prototype.save方法中以及根据对象是否isNew来保存或更新model.

// mongoose/lib/model.js Model.prototype.save = function save (fn) { var promise = new Promise(fn) , complete = handleSave(promise, this) , options = {}

if (this.schema.options.safe) { options.safe = this.schema.options.safe; }

if (this.isNew) { // send entire doc 新对象 var obj = this.toObject({ depopulate: 1 }); // 关联对象depopulate掉, 即 对象 --> ObjectID

if (!utils.object.hasOwnProperty(obj || {}, '_id')) {
  // documents must have an _id else mongoose won't know
  // what to update later if more changes are made. the user
  // wouldn't know what _id was generated by mongodb either
  // nor would the ObjectId generated my mongodb necessarily
  // match the schema definition.
  return complete(new Error('document must have an _id before saving'));
}

this.$__version(true, obj);
this.collection.insert(obj, options, complete);            // 插入
this.$__reset();
this.isNew = false;                                                     // 标记
this.emit('isNew', false);
// Make it possible to retry the insert
this.$__.inserting = true;

} else {
// Make sure we don’t treat it as a new object on error, // since it already exists this.$__.inserting = false;

var delta = this.$__delta();

if (delta) {
  if (delta instanceof Error) return complete(delta);
  var where = this.$__where(delta[0]);
  this.$__reset();
  this.collection.update(where, delta[1], options, complete);       // 增量更新
} else {                           // 没有脏数据
  this.$__reset();
  complete(null);
}

this.emit('isNew', false);

} };

回到顶部