问题描述
我正在尝试遵循一种使用NodeJS和MysqL管理模型的模式来完成以下任务:
customer = new Customer(1);
customer.name = "John Doe";
customer.save();
为完成上述工作,我想要一个构造函数,该构造函数将接收客户ID,从DB查询客户,然后将对象值设置为返回的值(请参见下文)。在设置对象值返回未定义状态时,我遇到了困难。这是最好的方法吗?
class customer {
constructor(id){
if (id) {
this.load(id);
}
}
load(id){
db.query("SELECT * FROM customers WHERE id = " + id,function (err,res){
if (err) {
console.log(err);
} else {
this.id = res[0].id;
this.name = res[0].name;
this.email = res[0].email;
}
});
}
save(){
let sql = "UPDATE customers SET name = ?,email = ? WHERE id = ?";
let data = [this.name,this.email,this.id];
db.query(sql,data,res){
if (err) {
console.log(err);
} else {
console.log("Updated customer " + this.id);
}
});
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)