![](/img/trans.png)
[英]What is The Best way to get date value in JavaScript to send in MongoDB.?
[英]What is the best way to write a .find query in a GET request with mongodb?
我正在嘗試發出 GET 請求,以便它只返回存儲在我的數據庫中的最后一項。 我可以在 mongo shell 中得到我想要的答案(見下文),但我不知道如何在我的 GET 路由中編寫查詢。 我正在使用 ejs 模板,因此我還需要通過 res.render 傳遞響應。 我對編程還是有點陌生,所以如果這個問題沒有應有的簡潔,請原諒我。
我的 mongo shell 查詢: Blog.find().sort({_id:-1}).limit(1)
我希望下面的代碼可以為您提供有關如何使用 express 和 EJS 構建代碼的提示。
app.get("/", async (req, res) => {
try {
const blogItem = await Blog.find().sort({_id:-1}).limit(1);
// Render the page with the result
res.render("your-page.ejs", { blog: blogItem });
} catch (error) {
// Handle errors here
res.render("500.ejs");
throw error;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.