node.jsを初めて使用し、一部のコマンドが重複するという断続的な問題が発生しています。dbインタラクションを残りのコードから分離しようとしていて、適切に分離していないという事実と関係があるのではないかと思います。次のようにtransaction.jsというファイルがあります。
var mongoose = require('mongoose');
mongoose.connect('mydb');
function Transaction(){
var actions = [];
this.Add = function(query){
actions.push(query);
};
this.Commit = function(){
for (var i = 0; i < actions.length; i++) {
actions[i]();
}
actions = [];
};
}
exports.Transaction = Transaction
私は新しいトランザクションを開始します
var transactionlib = require('../DB/transaction');
var transaction = new transactionlib.Transaction();
とトランザクションを呼び出します
exports.PostHome = function(req, res){
var id = new ObjectId(req.body.objectId);
transaction.Add(function(){
models.Story.findOne()
.where('_id').equals(id)
.exec(function(err, story){
saveOrUpdateStory(err, story, req, res);
});
});
transaction.Commit();
};
saveOrUpdateStory内では、さらに多くのdb呼び出しが行われていることに注意してください。
This seems to work fine but now and then it appears to duplicate the command (a submission will be added twice). My current theory is that this has to do with two people submitting two commands at the same time and the transaction list being shared between both of them. I'm not sure of this though and would love some help. Any criticism on my code structure would also be appreciated as I'm still learning best practices in node.