使用node-mysql编写MySQL Node.js模型

时间:2011-12-05 17:32:25

标签: mysql node.js models

我正在尝试使用node-mysql找到一些编写MySQL模型的好方法。

这是我到目前为止所拥有的:

var client = app.settings.client; // Client is set in Express settings

var table = 'users';

var User = function() {

}

// Create the user with data from Facebook
User.prototype.createFromFacebook = function (name, first_name, last_name, email, location, gender, facebookId, facebookToken, callback) {
  client.query(
    'INSERT INTO ' + table +
    ' SET name = ?, first_name = ?, last_name = ?, email = ?, location = ?,' +
    ' gender = ?, facebook_id = ?, facebook_token = ?',
    [ name, first_name, last_name, email, location, gender, facebookId, facebookToken ],
    function selectCb(err, results, fields) {
      if(err) {
        callback(err);
      } else {
        callback(null, results);
      }
    }
  );
}

// Get user with just their email address
User.prototype.getByEmail = function (email, callback) {
  client.query(
    'SELECT * FROM ' + table +
    ' WHERE email = ?',
    [ email ],
    function selectCb(err, results, fields) {
      if(err) {
        callback(err);
      } else {
        callback(null, results);
      }
    }
  );
}
module.exports = User;

对此的任何批评或改进都会很棒。谢谢!

3 个答案:

答案 0 :(得分:1)

作为改进,您可以重构代码

  1. 用于数据库连接的数据源对象
pywin32
  1. 创建UserSchema模型user.js定义字段,数据类型,验证规则等。

user.schema.js

const db = require(__dirname + '/myDatabaseInstance.js');

  1. 创建Controller.js,您可以在其中找到findAll,findById,创建,更新,删除,搜索API方法。
{
 "ID" : {
      "field" : "id",
       "type" : 'integer',
       "validation_rules" : "onlyInteger"     
  },
"name" : {
      "field" : "name",
      "type" : "string",
      "validation_rules": "usernameregex"   
 }
}

  1. 使用用户模式创建扩展到通用controller.js的user.js
 class _controller {
        constructor(object, model_schema) {
            this._object = object;
            this._model_schema = model_schema;
        }
        setId(_id) {
            this.id = _id;
        }

        validateRules(validation_rules) {
            return new Promise((resolve, reject) => {
                let error = {};
                let validation = new Validator(this._object, validation_rules);
                if (validation.fails()) {
                    error.type = "validation";
                    error.errors = validation.errors.errors;
                    reject(error);
                } else {
                    resolve(true);
                }
            });
        };

        create() {
            return new Promise((resolve, reject) => {
                let response = {};
                let error = {};
                this.validation_rules= 
                UserSchema.getRules(this._model_schema).get_validation_rules;
                this
                    .validateRules(this.validation_rules )
                    .then(validation_result => {
                        db.insert(this.table, this._object)
                          .then(result => {
                                response.status = 201;
                                resolve(response);
                            });

                    })

            });
        }
})

您可以在user.js代码中添加新功能。

答案 1 :(得分:0)

你的方式看起来很好。

确保当您收到错误时:

if (err) {
return callback(err)
}

或者只是像你一样使用其他人。

仅仅为了批评,我就是这样做的:

var db = require(__dirname + '/myDatabaseInstance.js');

var create = function (vals, next) {
  db.query('Insert INTO users SET ?', vals, next);
};

var load = function (selector, next) {
 db.query('SELECT * FROM users WHERE ?', selector, function (err, vals) {
   if(err) { 
     return next(err);
    }
    //at this point you could return a user object
    //next(new User(vals[0]));
     //or just return the array.
    next(null, vals);
 });
};
module.exports = create;
module.exports = load;

我这样称呼

var User = require(__dirname + '/user.js');
User.load({'id' : 1}, function (err, vals) {
  if (err) throw err;
  console.log(vals);
});

我个人的偏好是不为我的模型使用实例。我发现当我有关系时,它开始变得混乱。

例如,假设您有一个博客,其帖子存储在与用户相关的单独表格中。很容易让User对象有一个帖子数组。现在,如果更改此posts数组,则必须记住将更改后的用户保存到数据库中。我一直在忘记,所以我只是停止使用实例。

答案 2 :(得分:0)

Create model name abc.js with following code:
var mysqlModel = require('mysql-model');
var MyAppModel = mysqlModel.createConnection({
  host: 'localhost',
    user: 'ghgh',
    password: 'gfhgfh',
    database: 'gfhgh',
});


movie = new MyAppModel({tableName: "users"});



Now use this as following :
var abc = require(__dirname+'/routes/abc')
movie.find('id','all', function(err, rows) {
//console.log(rows)
})
movie.query("SELECT * from users", function(err, rows) {   
});
var value  ={'name': "value3"};
movie.save(value);