这与其说是一个问题,不如说是一个咨询请求.我找不到资源来判断我的方法的有效性,所以我想听听MongoDB专家的意见.
我在玩MongoDB,想出了这个中间件方法,将客户机传递给我的路由.我有一个快速中间件:
const addClientToRequest = async (req, _, next) => {
const client = new MongoClient(uri);
await client.connect();
req.client = client;
next();
};
app.use(addClientToRequest);
之后,我使用req.客户端在我的路径中访问我的数据库.
app.get("/:id", async (req, res) => {
const client = req.client;
const id = req.params.id;
try {
const data = await client.db("mydb").collection("mycollection").findOne({ id });
if (data) return res.status(200).json(data);
} catch (error) {
return res
.status(500)
.json({ message: "Error fetching requested data", error });
}
return res.status(404).json({ message: "Requested data cannot be found" });
});
这种方法会有什么问题?像这样使用MongoDB客户端可以吗?