【问题标题】:What is the best way to write a .find query in a GET request with mongodb?使用 mongodb 在 GET 请求中编写 .find 查询的最佳方法是什么?
【发布时间】:2020-04-24 12:25:51
【问题描述】:

我正在尝试发出 GET 请求,以便它只返回存储在我的数据库中的最后一项。我可以在 mongo shell 中得到我想要的答案(见下文),但我不知道如何在我的 GET 路由中编写查询。我正在使用 ejs 模板,所以我还需要通过 res.render 传递响应。我对编程还是有点陌生​​,所以如果这个问题不够简洁,请原谅我。

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

【问题讨论】:

  • 如果没有看到 GET 路由的服务器代码,这是不可能说的。您的服务器如何解析 URL 参数?
  • 您可以在GET 中传递id 请求类似localhost:8080/mypath?id=1 并从query 参数中读取id 值。使用nodejs and expressjs查看how to write a microservice上的示例代码
  • 以下是我如何编写初始请求以取回所有项目的示例:app.get("/index", (req, res) => { Blog.find({}, (err, allBlogs) => { if (err) { console.log("Something went wrong:", err); } else { res.render("index", { blogs: allBlogs }); } }); });

标签: javascript node.js mongodb express ejs


【解决方案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; 
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多