For example, I have
[
{ name: "John" },
{ name: "Mike" },
{ name: "Homer" },
{ name: "Bart" },
{ name: "Dmitry" },
{ name: "Dan" }
]
How will I choose many objects with mongoose, if I use .limit(2)
I will get [{ name: "John" }, { name: "Mike" }]
, I need to choose [{ name: "Bart" }, { name: "Dmitry" }]
. In default JS this method looks like .slice(3,5)
. How will I do it with mongoose?
2
Answers
You can achieve this in mongodb by using
skip(3).limit(2)
.In Mongoose you can achieve this with
myModel.find({}, 'name', {skip: 3, limit: 2})
, you just have to insert values ofskip
andlimit
you want in third parameter offind
.Here’s documentation with an example of skip and here’s a link to a more popular answer of similar problem.
Edit: Note that this is a short-sighted solution, you should use something else for large or changing database.
You can try something like this:
Model.find({name: {$in: ["Bart", "Dmitry"]}});