Can I require the attribute to be set in the mongodb collection? (not zero)

Can I define a schema in mongodb that requires certain attributes. Very similar to NOT NULL in SQL. If possible. What is the syntax for this?

I am using node.js and mongoose. mongoose v3.6.15 mongodb v2.4.5

Edit The answer provided by Charles A is correct, but looking through the documentation, I found that in the mongoose you can also define the field as required to write off the circuit as follows:

 foo : { bar : { type : String, required : true } } 
+7
mongodb mongoose
source share
3 answers

In Mongoose, you can use validator to check if a field has been set before saving. As far as I know, there is no way to indicate on the diagram that a field is required, so this requires a bit more boilerplate code.

+7
source share

For required fields, use $ AND in the collection validator with "$ exists: true":

 db.createCollection("foo", { validator: { $and: [ {"bar": {$type: "string", $exists: true}} ] }) 

more info here https://www.compose.com/articles/document-validation-in-mongodb-by-example/

+1
source share

The general answer to this question does not apply to Mongoose, this is a simple MongoDB question about whether you might need a specific key in each document.

Answer: YES. Create a unique index in this collection. Index must be required. There will be only one document with a field that is null, which ensures the presence of this field in all documents. Hit it "rare."

See: http://docs.mongodb.org/manual/core/indexes/

In particular, the section on unique indices. Please note: this will not work for hashed fields.

-3
source share

All Articles