我正在使用node和express开发一个restful 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;
});
来自控制器。
Update
好的,我现在使用的是 node-postgres,第 10 页。我看到更好了,谢谢大家的建议。
我想创建一次数据库实例,并在任何地方调用它,特别是在控制器中
我可以使用 app.local 保存我的客户端吗?,连接,执行查询,然后关闭它。在任何地方都可以这样做