0
我有以下组合,NodeJS,Express,MongoDB和Mongoose。我已经实施了与猫鼬承诺允许同时编辑的随机数。请参阅以下:NodeJS,ExpressJS,Mongoose 4.4,Nonce用于并发和Document.update
//schema
var item_schema = {
//_id: {type: Schema.ObjectId, required: true},
name: {type: String, required: true, index: { unique: true }},
code: {type: String, required: true, index: { unique: true }},
date_time_created: {type: Date, required: true},
date_time_updated: {type: Date, required: true},
nonce: {type: Schema.ObjectId}
};
//model
var item_model = mongoose.model('item', schema);
//update
var concurrency_update = function(req, res, retries) {
var promise = model.findById(req.params.id).exec();
var updated_nonce = mongoose.Types.ObjectId();
promise.then(function(document){ //find document response
if(!document) {
res.status = 404;
return Promise.reject({ "message" : req.params.id + ' document does not exist' });
}
var now = new Date();
if(req.body.code) {
document.code = req.body.code;
document.date_time_updated = now;
}
if(req.body.name) {
document.name = req.body.name;
document.date_time_updated = now;
}
if(!document.nonce) {
document.nonce = updated_nonce;
var old_nonce = document.nonce;
}
else {
var old_nonce = document.nonce;
document.nonce = updated_nonce;
}
return document.update({ "_id" : req.params.id, "nonce" : old_nonce }).exec();
}).then(function(raw){ //update response
var number_affected = raw.n;
console.log(raw);
if(!number_affected && retries < 10){
//we weren't able to update the doc because someone else modified it first, retry
console.log("Unable to update, retrying ", retries);
//retry with a little delay
setTimeout(function(){
concurrency_update(req, res, (retries + 1));
}, 20);
} else if (retries >= 10){
//there is probably something wrong, just return an error
return Promise.reject({ "message" : "Couldn't update document after 10 retries in update"});
} else {
res.json({"message": req.params.id + ' document was update'});
}
}).catch(function(err){
res.send(err.message);
});
并发更新是基于的是: http://www.mattpalmerlee.com/2014/03/22/a-pattern-for-handling-concurrent/
和阅读猫鼬文档更新是基于关闭了这一点。但是,当代码进入最终的.then(/ /更新响应)时,我看到raw.n(numberAffected)= 1但数据库永远不会更新?
答案可能很接近但我很想念它。 我对此有什么想法?
无论你做什么,如果你首先使用任何类型的'.findOne()'变体从数据库中检索,你将会遇到问题。请使用['.update()'](http://mongoosejs.com/docs/api.html#model_Model.update)或['.findOneAndUpdate()'](http://mongoosejs.com/docs/ api.html#model_Model.findOneAndUpdate)变体以及[原子更新修饰符](https://docs.mongodb.org/manual/reference/operator/update-field/)。这些都是为了在当前状态下“就地”修改,而不用担心在获取和重新保存数据之间可能发生的情况。改变你的模式。 –
@blake_seven - 所以如果我理解你的评论,如果你使用原子更新修饰符(例如$ set和$ remove),那么nonce是不需要的。我会尝试并发布解决方案。 – thxmike