使用Mongoose,我想用MongoDB进行查询并排序和限制得到的结果。我正在使用Node.js这样做,所以我正在使用回调。
到目前为止,我已经设法将结果排序如下:
myModel.find({ $query: {}, $orderby: { created_at : -1 }}, function (err, items) {
callback( null, items )
});
如何限制选择的结果和索引以及要获取的项目数?
使用本机mongodb:http://mongodb.github.io/node-mongodb-native/api-genic/collection.html#find
myModel.find(filter)
.limit(pageSize)
.skip(skip)
.sort(sort)
.toArray(callback);
您还可以在查询中指定项目:
myModel.find(filter, {sort: {created_at: -1}, limit: 10}, function(err, items){
});
节点mongodb本机中没有$ orderby,因此我不确定您使用的是哪个库或其他工具。
...
既然您已经弄清了猫鼬(通常我建议不要这样做):
myModel.find(filter).limit(10).exec(function(err, items){
//process
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句