0

我是 node.js 的新手,我遇到了一些重复的命令的间歇性问题。我认为这可能与我试图将我的数据库交互与我的其余代码分开并且我没有正确隔离它的事实有关。我有一个名为 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 中有更多的数据库调用发生。

这似乎工作正常,但有时它似乎重复命令(提交将被添加两次)。我目前的理论是,这与两个人同时提交两个命令以及他们之间共享的事务列表有关。不过,我不确定这一点,并希望得到一些帮助。对我的代码结构的任何批评也将不胜感激,因为我仍在学习 node.js 的最佳实践。

4

1 回答 1

1

If anyone is coming across this with the same issue I'd just like to clarify what was wrong. I had a Homecontroller.js which I was never creating a new instance of, so all requests were accessing a global instance of it. The result was that two requests could fire the same transaction twice if they were within a short enough time period.

In Hindsight, it's a good idea to wrap your controllers in functions (google "Module pattern") so that this doesn't happen.

于 2013-04-29T03:20:07.673 回答