E
E
ExcaliBUR952022-02-27 12:50:21
MongoDB
ExcaliBUR95, 2022-02-27 12:50:21

How to set a limit in working with arrays in a database (mongoose)?

621b48d3b97f5111711566.png621b48d9af623532643225.png
In general, here is the circuit and the controller, the task is this. It is
necessary to set a limit on renting books, and if there are more than 3 books, then the boolean type becomes false, (it is commented out because the node was cursing, I decided to figure it out later, but I will be glad if they tell me here too)
tried limit() didn't work, doesn't work with findByIdAndUpdate(), tried ternary, if els, doesn't work either.. googled, didn't find anything like that

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rag'n' Code Man, 2022-02-27
@iDmitriyWinX

I'll start a little off the point of the question, but it will also come in handy for you.

  1. We call the model not Clients, but Client. We use plurals when talking about an array. You are creating a model of one client, not several.
  2. isBlocked- useless field. And it swears, because the class is waiting Boolean, and you are passing the type.
  3. Most likely, your client cannot have two identical books, so we use $addToSet instead$push of .

And now to your question.
Just start from the size of the array.
First, get the client by id, and if not found, then throw it away 404.
Then you check for the length of his books, and if it is less than 3 (I advise you to take it to a constant), then do it $addToSet, otherwise you throw it away Bad Requestor something like that.
I strongly advise you to add a book as a separate request, and not arr.pushon the document and the subsequent one save.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question