【发布时间】:2016-03-26 04:53:23
【问题描述】:
如何使用 _id 检索在我的集合中创建的最新文档?
我正在尝试通过以下方式在我的 Web 应用程序中实现分页:
- 检索我的页面中加载的最后一个文档的 _id
- 检索大于下一页中最后一个文档的“_id”的文档 (http://tldrify.com/dcj)
我采用这种方法的原因是因为我试图利用存储数据中的自然顺序 - 存储在文档中的 id。
获取下一组帖子的示例:
Posts.find({ _id : { $gt : lastObjectId } }, function(){
if(error){
console.log('error in get_next_posts');
} else {
response.json(results);
}
}).limit(5)
我的猫鼬模式:
var PostSchema = new mongoose.Schema({
upvotes: {type: Number, default: 0},
comments: Array,
imageURI: String,
caption: String,
location: Object,
hashtag: String
});
据我了解,Mongo 的文档已经按照文档从最旧到最新排序:
"MongoDB 在创建集合时为所有集合创建 _id 索引,它是 _id 字段上的升序唯一索引。 (https://docs.mongodb.org/v3.0/core/index-single/)"
在将一些帖子推送到我托管在 Heroku 上的 mongoDB 数据库后,最初一切都运行良好(似乎按升序发布)
Post1 id --- 56756e2047b977030017b36d
Post2 id --- 56756e4f47b977030017b36e
Post3 id --- 56756e8447b977030017b36f
Post4 id --- 56756ef747b977030017b370
Post5 id --- 56756f3f47b977030017b371
Post6 id --- 56756f7247b977030017b372
但是在将我的第 7 和第 8 个帖子添加到集合后,我的 Mongo 数据库似乎突然停止按升序排序帖子,这意味着我不能再使用以前的 mongoose 查询。
我不确定为什么在我的数据库中发布了几篇帖子后升序停止了 - 任何人都知道为什么?
Post1 id --- 56756e2047b977030017b36d
Post7 id --- 5675727647b977030017b374 <-- why are they here now?
Post8 id --- 5675744847b977030017b375 <--
Post2 id --- 56756e4f47b977030017b36e
Post3 id --- 56756e8447b977030017b36f
Post4 id --- 56756ef747b977030017b370
Post5 id --- 56756f3f47b977030017b371
Post6 id --- 56756f7247b977030017b372
更新:这就是我最终获得 _id 最旧帖子的方式:
Post.find({}, function(error, results) {
if(error) {
console.log('error in show');
} else {
console.log('show query successful');
response.json(results);
}
}).sort({_id:1})
【问题讨论】:
-
为了根据 _id 获取最旧的帖子,我最终应用了 .sort({_id:1})。
标签: mongodb mongoose database nosql