【问题标题】:mvc with node/express and mysql带有 node/express 和 mysql 的 mvc
【发布时间】:2019-04-08 02:40:45
【问题描述】:

我越来越糊涂了。我在 mySql 中看到的所有教程都以这样的方式结束:

在模型/dbconnection.js 中

    var mysql = require('mysql');
port = process.env.PORT || 3333;

if (port == 3333) {
    var connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: 'root',
        database: 'nameDataBase',
        insecureAuth: true
    });
} else {
    console.log("Error");
}

connection.connect();
module.exports = connection;

然后在 routes/user.js 中

...    

router.delete("/:id", verifyToken, (req, res) => {
        const newLocal = "DELETE FROM login_user WHERE id = ?";
        connection.query(newLocal, [req.params.id], (err,rows,fields) => {
            if (err) {
                res.sendStatus(500);
                return;
            }
            console.log(rows.affectedRows);
            res.status(200).send({delete: rows});
        });

});

module.exports = router;

模型和控制器没有在这里混在一起吗?如果明天我想更改数据库的类型,我必须在模型和路由中进行更改。我不应该在 models/user.js 中创建诸如 getAllUsersBlaBla(params) 之类的函数,然后从 routes/user.js 调用它吗?

【问题讨论】:

    标签: mysql node.js express


    【解决方案1】:

    我同意。路由器中不应该有任何数据库查询,它被认为是 MVC 中控制器的一部分。

    模型应该围绕可以从控制器调用的数据库查询提供包装函数。

    很多节点应用程序(可能还有教程)会选择简单性而不是模块化,这就是为什么你会看到这样的代码。

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2014-06-29
      • 2015-05-25
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多