这不是一个问题,而是一个咨询请求。我找不到资源来检查我的方法是否有效,因此我想听一下MongoDB专家的意见。
我正在使用MongoDB并构建了这个中间件方法来将客户端传递给我的路由。我有以下Express中间件:
这种方法存在什么问题?使用MongoDB客户端是否可以这样做?
我正在使用MongoDB并构建了这个中间件方法来将客户端传递给我的路由。我有以下Express中间件:
const addClientToRequest = async (req, _, next) => {
const client = new MongoClient(uri);
await client.connect();
req.client = client;
next();
};
app.use(addClientToRequest);
之后,我在我的路由中使用req.client来访问我的数据库。
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客户端是否可以这样做?