简体   繁体   English

使用 mongodb 在 GET 请求中编写 .find 查询的最佳方法是什么?

[英]What is the best way to write a .find query in a GET request with mongodb?

I am trying to make a GET request so that it only returns the last item stored in my database.我正在尝试发出 GET 请求,以便它只返回存储在我的数据库中的最后一项。 I can get the answer I want in the mongo shell (see below), but I'm at a loss as to how to compose the query in my GET route.我可以在 mongo shell 中得到我想要的答案(见下文),但我不知道如何在我的 GET 路由中编写查询。 I am using ejs templates, so I will also need to pass the response through the res.render as well.我正在使用 ejs 模板,因此我还需要通过 res.render 传递响应。 I am still kind of new to programming so forgive me if this question isn't as concise as it should be.我对编程还是有点陌生​​,所以如果这个问题没有应有的简洁,请原谅我。

My mongo shell query: Blog.find().sort({_id:-1}).limit(1)我的 mongo shell 查询: Blog.find().sort({_id:-1}).limit(1)

I hope the code below gives you a hint on how to structure your code using express and EJS.我希望下面的代码可以为您提供有关如何使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM