简体   繁体   English

MongooseJS - 限制子文档中的文档数

[英]MongooseJS - limit number of documents in subdocument

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. 在我的应用程序中,可以使用ajax将元素添加到子文档中,因此重要的是我要防止恶意用户添加一些荒谬的条目。

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. 我可以想到一种方法,即查询父文档,检查子文档中的元素数量,如果它小于X,保存它。 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(). 我宁愿更喜欢使用update(),而不是findOne()和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. 我不知道是否可以使用一个subdoc,我用一个普通的对象做了。 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. 如果处理对象,请先检查密钥是否为数字。

You can make an array limit in Mongoose, using a custom validate function, with something like: 您可以使用自定义validate函数在Mongoose中创建数组限制,例如:

validate: [v => v.length <= MAX, 'message']

where MAX is some maximal number of elements, and 'message' is a message to show on validation failure. 其中MAX是一些最大数量的元素, 'message'是验证失败时显示的消息。 See: 看到:

http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate 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. 但是如果数组太长,你就无法为MongoDB提出一个失败的请求,因为MongoDB没有模式的概念,而且需要做你想做的事情。 Schemas are only present in Mongoose. 模式仅存在于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. 因此,如果您想直接使用MongoDB,那么不仅您无法在一个请求中执行它,实际上情况要差得多 - 您也无法消除竞争条件,因为MongoDB不支持事务,因此您无法保证永远不会超过你的限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM