模型对象构造函数中的节点mysql查询

node-mysql query in model object constructor

本文关键字:节点 mysql 查询 对象 构造函数 模型      更新时间:2023-09-26

我是javascript中的beginer。我尝试编写一个与Express和node-mysql一起使用的模型。它定义了类Place
当我创建一个对象实例:var p = new Place(10);时,它应该初始化对象并填充变量。但是初始化数据存储在数据库中,并且查询是异步的,所以我认为对象是首先创建的,我不知道从数据库返回的数据会发生什么,也不知道如何正确初始化对象实例变量。

var db = app.db; // app is set as GLOBAL
// constructor
var Place = function(place_id) {
    this.getPlaceById.call(place_id, function(err, result){
        if (err) throw err;
        this.id = result.id;
        this.title = result.title;
        this.city = result.city;
        this.address = result.address;
    });
}
Place.prototype.getPlaceById = function (place_id, callback) {
    db.query(
        'call getPlaceById(?);', /*  call stored procedure  */
        [ place_id ],
        function(err, results, fields) {
            if(err) {
                callback(err);
            } else {
                callback(null, results[0][0]);
            }
        }
    );
}
module.exports = Place;

结果我得到了一个奇怪的错误:

function(place_id) {
...
} has no method 'replace'
    at Object.SqlString.escape (.../node_modules/mysql/lib/protocol/SqlString.js:40:13)
    at .../node_modules/mysql/lib/protocol/SqlString.js:72:22
    at String.replace (native)

如果我留下空的构造函数,只调用:

p.getPlaceById(10, function(err,r) {
    console.log(r)
});

它工作时没有错误,并返回正确的数据。

我找到了解决方案:

var Place = function(place_id, fn) {
    var self = this;
    Place.prototype.getPlaceById.call(this, place_id, function(err, result){
        if (err) {
            fn.call(self, err)
        }
        else {
            self.id = result.id;
            self.title = result.title;
            self.city = result.city;
            self.address = result.address;
            fn.call(self);
        }
    });
}

并创建一个对象实例以便:

var p = new Place(place_id,function(err,result){
    if (err)
        console.log(err)
    else
        console.log(p);
});