【发布时间】: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