[英]Query a MongoDB Server Using Express (Node.js project)
I've created a route in a Node.js project to render all "logs" from a MongoDB database to a Web page: 我已经在Node.js项目中创建了一条路由,以呈现从MongoDB数据库到网页的所有“日志”:
app.get('/api/logs', function (req, res) {
Log.find( function (err, logs) {
res.json(logs);
});
});
I want to modify this query to (1) limit the response to 10 logs and (2) display the logs in reverse chronological order (from most recent to least recent). 我想将此查询修改为(1)将响应限制为10个日志,以及(2)按相反的时间顺序显示日志(从最新到最近)。 If I try the below code, nothing will render to my page and my Node server gives the following error: Error: sort() only takes 1 Argument . 如果尝试以下代码,则任何内容都不会呈现到我的页面,并且我的节点服务器给出以下错误: 错误:sort()仅采用1个参数 。
app.get('/api/logs', function (req, res) {
Log.find().limit(10).sort({$natural:-1}, function(err, logs){
res.json(logs);
});
});
The above snippet DOES work if I type it directly into my Monog console as a single query: Log.find().limit(10).sort({$natural:-1}) Is there a different way to write this to grab the information I want? 如果我将其作为单个查询直接输入到Monog控制台中,上述代码段将起作用: Log.find()。limit(10).sort({$ natural:-1})是否有其他方法可以编写此代码来进行抓取我想要的信息? Thanks for your suggestions! 感谢您的建议!
This works perfectly: 这完美地工作:
app.get('/api/logs', function (req, res) {
Log.find().limit(10).sort(-fieldToSort).exec(function(err, logs){
res.send(logs)
})
});
The -fieldToSort sorts the field in a descending order as you requested. -fieldToSort根据您的要求以降序对字段进行排序。 fieldToSort is the field name you want to sort. fieldToSort是要排序的字段名称。
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.