Using Mongoose for MongoDB query. I have inserted 100 records using code below:
console.log("begin inserting posts...");
let i;
for (i = 0; i < 100; i++) {
const post = new Post({
author: {
name: "name" + i
},
source: "Qizhongyouxiang",
url: "https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg",
title: "image title"
});
post.save();
}
Since the insertion is in sequence, so the first five records should be with name
from name0
to name4
.
This is how the data look like through Compass:
{"_id":{"$oid":"5dfc4386006c085bda8916db"},"author":{"name":"name0"},"source":"Qizhongyouxiang","url":"https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg","title":"image title","__v":{"$numberInt":"0"}}
{"_id":{"$oid":"5dfc4386006c085bda8916dc"},"author":{"name":"name1"},"source":"Qizhongyouxiang","url":"https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg","title":"image title","__v":{"$numberInt":"0"}}
{"_id":{"$oid":"5dfc4386006c085bda8916dd"},"author":{"name":"name2"},"source":"Qizhongyouxiang","url":"https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg","title":"image title","__v":{"$numberInt":"0"}}
{"_id":{"$oid":"5dfc4386006c085bda8916df"},"author":{"name":"name4"},"source":"Qizhongyouxiang","url":"https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg","title":"image title","__v":{"$numberInt":"0"}}
{"_id":{"$oid":"5dfc4386006c085bda8916e0"},"author":{"name":"name5"},"source":"Qizhongyouxiang","url":"https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg","title":"image title","__v":{"$numberInt":"0"}}
Then I use the following code to retrieve 3 records:
Post.find().limit(sizeLimit).then(posts => {
console.log(posts.length);
console.log(posts);
res.json(posts);
});
The output is like this:
3
[
{
author: { name: 'name0' },
_id: 5dfc4386006c085bda8916db,
source: 'Qizhongyouxiang',
url: 'https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg',
title: 'image title',
__v: 0
},
{
author: { name: 'name1' },
_id: 5dfc4386006c085bda8916dc,
source: 'Qizhongyouxiang',
url: 'https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg',
title: 'image title',
__v: 0
},
{
author: { name: 'name4' },
_id: 5dfc4386006c085bda8916df,
source: 'Qizhongyouxiang',
url: 'https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg',
title: 'image title',
__v: 0
}
]
Any reason the records with name2
and name3
got skipped? If I set the limit to 5, name2
and name3
record will show after name4
.