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掉还是不行。
你用的mongoose是什么版本的? 我这边[email protected] 测试没有问题, 对应的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);
} };