我需要帮助。 我有这个节点项目从一开始就在工作。 最近我开始收到关于mongoose无法同时更新__v和__v的错误(详情如下) 我的第一个想法是猫鼬的新更新带来了这个,但我不确定。 任何帮助将不胜感激。 感谢
/.../node_modules/mongoose/lib/utils.js:413
throw err;
^
MongoError: exception: Cannot update '__v' and '__v' at the same time
at Object.toError (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:114:11)
at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1131:31
at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1846:9
at Server.Base._callHandler (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:478:18
at MongoReply.parseBody (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
at null.<anonymous> (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:436:20)
at EventEmitter.emit (events.js:95:17)
at null.<anonymous> (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
at EventEmitter.emit (events.js:98:17)
修改 看起来当我尝试保存时会抛出错误。这是我调用的保存方法;
save: function (callback) {
// A Helper function
function setID(instance, id) {
instance._id = id;
};
var self = this; // Preserve reference to the instance
var update = Utils.clone(this);
delete update._id; // Delete the _id property, otherwise Mongo will return a "Mod on _id not allowed" error
// Prepare updates for saving
for (var key in update) {
if (update[key] == undefined)
delete update[key];
if (key == 'company' || key == 'local_currency')
update[key] = update[key].getID();
}
PreferenceModel.save(this._id, update, function (err, savedDoc) {
if (err) callback(err);
else {
if (!self.getID()) // If the object didn't previously have an _id property
setID(self, savedDoc._id);
callback(null, self);
}
});
}
以及我称之为的地方;
preference.save(function (err, savedPreference) {
if (err) callback(err);
else callback(null);
});
此外,还有PreferenceModel.save方法;
function save(id, update, callback) {
Preference.findByIdAndUpdate(id, update, {upsert: true}, function (err, savedDoc) {
if (err) callback(err);
else callback(null, savedDoc);
});
}
答案 0 :(得分:2)
我建议你将_id相关删除逻辑放入你的mongoose模型模式定义文件中:
var UserSchema = new mongoose.Schema(fieldDefinitions);
// Ensure virtual fields are serialised.
UserSchema.set('toJSON', {
virtuals: true
});
// Ensure able to see virtual fields output when using console.log(obj)
UserSchema.set('toObject', {
virtuals: true
});
UserSchema.options.toJSON = {
transform : function(doc, ret, options) {
console.log('--> ' + require('util').inspect( ret._id.id ));
ret.id = ret._id.id;
delete ret._id;
delete ret.__v;
return ret;
},
virtuals: true
};
然后在你的回调中执行toJSON:
var processedJson = resultDoc.toJSON();
检索处理后的版本,它很好地隐藏了可重复使用的逻辑 注意:toJSON()也由JSON.stringify()
神奇地执行