如何将数据从模型发送到控制器节点JS

发布于 2025-02-02 19:41:32 字数 816 浏览 4 评论 0原文

我正在从路由中调用dotoller中的getIndex函数,从模型中获取数据库,但是如何从数据库中获取数据,但是如何存储数据并将其发送给Contoller以及如何在Contoller中接收。

这就是我连接数据库的方式

const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'practice',
password: ''
});
module.exports = pool.promise();

模型

const db = require('../database');

module.exports = class User {   
fetchAll(){
     db.execute('SELECT * FROM users')
     .then(([rows,fieldData]) => {
         console.log(rows); //giving the required data
      })
}
}

控制器

const User = require('../model/user');

exports.getIndex = (req,res,next) => {
const user = new User();
user.fetchAll();
res.render('index');
};

I am calling getIndex function in contoller from routes and fetchAll from model is getting data from database but how to store the data and send it to contoller and how to receive in contoller.

This is how i have connected the database

const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'practice',
password: ''
});
module.exports = pool.promise();

model

const db = require('../database');

module.exports = class User {   
fetchAll(){
     db.execute('SELECT * FROM users')
     .then(([rows,fieldData]) => {
         console.log(rows); //giving the required data
      })
}
}

controller

const User = require('../model/user');

exports.getIndex = (req,res,next) => {
const user = new User();
user.fetchAll();
res.render('index');
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪淡了忧伤 2025-02-09 19:41:32

等待

这是一个很好的例子,说明在哪里使用承诺和在模态中

const db = require('../database');

module.exports = class User {
    fetchAll() {
        return (new Promise((resolve, reject) => {
            db.execute('SELECT * FROM users')
                .then(([rows, fieldData]) => {
                    resolve(rows); // return data
                })
        }))

    }
}

在控制器中执行此操作。

const User = require('../model/user');

exports.getIndex = async (req, res, next) => {
    const user = new User();
    let data = await user.fetchAll();
    res.render('index');
};

here is a good example of where to use promises and async/await

in modal do this

const db = require('../database');

module.exports = class User {
    fetchAll() {
        return (new Promise((resolve, reject) => {
            db.execute('SELECT * FROM users')
                .then(([rows, fieldData]) => {
                    resolve(rows); // return data
                })
        }))

    }
}

in the controller do this

const User = require('../model/user');

exports.getIndex = async (req, res, next) => {
    const user = new User();
    let data = await user.fetchAll();
    res.render('index');
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文