【发布时间】:2019-08-31 17:23:45
【问题描述】:
我正在用 node 和 exrpess 开发一个完整的 api,我的数据库是 postgresql,我需要使用 postgres 包 pg-promise。
我知道我需要将我的应用程序与 app.js 文件中的数据库连接起来,但我的问题是,我应该如何在我的端点中使用此连接。
我有路线,我正在使用控制器。
例如
app.js
//in this file, suppously I have to to the connection
const db = pgp('postgres://john:pass123@localhost:5432/products');
app.use('/products', productsRoute);
products.js(路由)
router.get('/', ProductsController.get_all_products);
products.js(控制器)
exports.get_all_products = (req, res, next ) => {
// Here i want to use de database connection to do the query to find all
//products in the database
}
如何访问连接以执行类似的操作
db.any('SELECT * FROM products WHERE active = $1', [true])
.then(function(data) {
// success;
})
.catch(function(error) {
// error;
});
来自控制器。
更新
好的,我现在正在使用 node-prostgres,pg。我看到更好,感谢人们的建议。
我想创建一次 de db 实例,并在任何地方调用它,特别是在控制器中
我可以使用 app.local 来保存我的客户端吗?连接,进行查询然后关闭它。在任何地方都可以这样做
【问题讨论】:
标签: node.js postgresql express