0

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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Donnle
  • 106
  • 6
  • This type of question had been answered before. You can find the answer to your question here: https://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array – Daniyal Malik May 24 '22 at 20:57

2 Answers2

1

You can try something like this:

Model.find({name: {$in: ["Bart", "Dmitry"]}});

Carlosdp7
  • 61
  • 3
0

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 of skip and limit you want in third parameter of find.

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.

DGX37
  • 304
  • 3
  • 12
  • Do you think that this approach is right for finding selected values? What if there is a large data set, would you still use this approach, I mean would this be handy? – Daniyal Malik May 25 '22 at 07:05
  • 1
    @DaniyalMalik I gave such an answer not as a scalable solution for any kind of database but just for this case, when there are few database entries and you just want to skip the first 3, `slice(3, 5)` but in mongoose. Obviously skip would be bad if database had thousands of entries or even if somebody added just one new entry. So to answer your question, no, on real database that changes and has a lot of values this is a bad solution. – DGX37 May 25 '22 at 07:17