Reputation: 16607
I wonder if there's a way to limit the number of elements in a (sub)document. In my app, elements can be added to the subdocument with ajax, so its important that I prevent adding a ridiculous number of entries by a malicious user.
I can think of one way, that is to query the parent document, check number of elements in the subdocument and if its less than X, save it. That however requires to query the whole document, just to update a little thing. I would rather much prefer to do everything with update(), instead of findOne() and save(). Is there a way?
Edit: It can be done without db lookup prior to updating. I don't know if it's possible to do with a subdoc, I did it with a plain object. Simply store your data in an array or better a classical object. Then before updating, validate key numbers, if key number is greater than the allowed - ignore it. Ofc if dealing with an object, check if the key is a number first.
Upvotes: 3
Views: 1044
Reputation: 111278
You can make an array limit in Mongoose, using a custom validate
function, with something like:
validate: [v => v.length <= MAX, 'message']
where MAX
is some maximal number of elements, and 'message'
is a message to show on validation failure. See:
http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate
But you cannot make a one request for MongoDB that would fail if the array is too long because MongoDB has no concept of schemas and that would be needed to do what you want. Schemas are only present in Mongoose.
So if you want to use MongoDB directly then not only you will not be able to do it in one request, it's actually much worse than that - you also cannot eliminate a race condition because MongoDB doesn't support transactions, so you cannot really guarantee that your limit will never be exceeded.
Upvotes: 2