使用从MongoDB获取的新数据更新对象属性

时间:2013-09-30 20:45:44

标签: javascript node.js mongodb

我正在尝试使用从MongoDB获取的新数据更新对象属性。以下代码不起作用。我不知道为什么?有人可以帮帮我吗?

 var UserDB = require('../models/user_model.js').UserModel;    
    function User(uid, username, credit, socket, seat, normal, bank, bankThree) {
            this.uid = uid;
            this.username = username;
            this.credit = credit;
            this.socket = socket;
            this.seat = seat;
            this.normal = normal;
            this.bank = bank;
            this.bankThree = bankThree;
            this.serverPerform = 0;
            this.actionTaken = false;
            this.cards = [];
            this.bet = 0;
            this.catched = false;
            this.action = false;
        }
        User.prototype.update = function(){
            var self = this;
            UserDB.findOne({uid:this.uid},function(err,doc){
                console.log(doc);
                if(!err){
                    self.username = doc.username;
                    self.credit = doc.credit; 
                    console.log(self); // work as expected
                }
            });

            console.log(self); // nothing change
        };
    var user = new User(1);
    user.update(); //nothing change

1 个答案:

答案 0 :(得分:0)

看起来你的mongo更新功能是ASYNCHRONOUS,所以当然你的回调里面的日志工作,而外面的那个没有。

User.prototype.update = function(callback){ //Now we've got a callback being passed!
    var self = this;
    UserDB.findOne({uid:this.uid},function(err,doc){
        console.log(doc);
        if(!err){
            self.username = doc.username;
            self.credit = doc.credit; 
            console.log(self); // work as expected
            callback(); //pass data in if you need
        }
    });
};

现在您已经通过了callback,您可以这样使用它:

var user = new User(1);
user.update(function() {
    //do stuff with an anonymous func
});

或者定义你的回调并将其传递给

function callback() {
    //do stuff
}

var user = new User(1);
user.update(callback);