0

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.

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.

Hindsightでは、これが起こらないように、コントローラーを関数(google "Module pattern")でラップすることをお勧めします。

于 2013-04-29T03:20:07.673 に答える