2

I'm getting confused. All the tutorials I see with mySql end up with something like this:

in models/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;

And then in 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;

model and controller aren't getting mixed here? If tomorrow I want to change the type of database, I have to make changes in the model and in the routes. Shouldn't I make functions such as getAllUsersBlaBla(params) in something like models/user.js and then call it from routes/user.js ?

0

1 Answer 1

4

I agree. There shouldn't be any database queries in the router, which is considered part of the controller in MVC.

The model should provide wrapper functions around database queries that can be called from the controller.

A lot of node apps (and probably tutorials) will choose simplicity rather than modularity, that's why you would see code like that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.