Set limits on mongo db collection

十年热恋 提交于 2020-03-05 12:20:18

问题


So, there are two limits I want to set in mondo db:

1. Only allow one document to be inserted into the dbs, and no more. This document cannot be deleted once added, BUT it can be modified. Also, no other documents can be added to that collection.

Only one value will be allowed under this schema.

{ "_id" : ObjectId("5800"), "seconds" : "120", "__v" : 0 }

No more new seconds will be allowed to be added in, and only the above document can be modified.

I have tried:

var numbersSchema = new mongoose.Schema({
  seconds: { type: Number, min: 60 }
},{ capped : true, size:4000,  max : 1 })

However I can still add multiple documents:

{ "_id" : ObjectId("5800c7f53c609009dc5800f4"), "seconds" : 390, "__v" : 0 }
{ "_id" : ObjectId("5800c81b3c609009dc5800f5"), "seconds" : 590, "__v" : 0 }

2.Set a min value on a schema entry field.

var numbersSchema = new mongoose.Schema({
  seconds: Number
})

So, in this case 'seconds' must be at least 60 seconds as the minimum value. I assume this needs to be changed in the schema, but I do not know how. Is it possible to add '>59' into the schema, or is there an option with mongo already?

Any tips would be appreciated!


回答1:


This can be easily achieved using Capped Collections in mongodb. you can set a limit on number of documents, so in your case you can set maximum number of documents to 1 as below:

db.createCollection("numbers", { capped : true, size:4000,  max : 1 } )

Also if you want to set your collection as capped from mongoose schema, you can do it using capped option as follows:

var numbersSchema = new mongoose.Schema({
  seconds: Number
},{ capped : true, size:4000,  max : 1 })

This collection will always hold only one document which can be updated. Note that the documents once inserted in capped collections can not be deleted. So this solves your deletion problem too.


Also the size option that you need to specify, can be any positive integer value, which will be converted internally by mongo to a minumum of 4096 bytes, or closest multiple of 256.

IMPORTANT:

The size argument is always required, even when you specify max number of documents. MongoDB will remove older documents if a collection reaches the maximum size limit before it reaches the maximum document count.

Source: MONGODB docs


Also, if you want to set the min or max value to the seconds, you can always use mongoose min-max validations. So the following schema should work for you.
var numbersSchema = new mongoose.Schema({
  seconds: { type: Number, min: 60 }
},{ capped : true, size:4000,  max : 1 })


来源:https://stackoverflow.com/questions/40039436/set-limits-on-mongo-db-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!