Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I require an attribute to be set in a mongodb collection? (not null)

Can I define a schema in mongodb which requires certain attributes to be set. Much like NOT NULL in SQL. If that is 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 mongoose it is also possible to define a field as required in the schema defenition like this:

foo : {
    bar : { type : String, required : true }
}
like image 201
Ludwig Magnusson Avatar asked Jul 30 '13 09:07

Ludwig Magnusson


People also ask

How do I make a field not null in MongoDB?

Basically, we can use the $exists a method to implement the not null in MongoDB. When <boolean> is valid, $exists coordinates with the records that contain the field, including reports where the field esteem is invalid. In case <boolean> is bogus, the question returns just the records that don't contain the field.

How do I check if a field is not null in MongoDB?

To query for is not null value, we can use the $ne operator as well as the $eq operator and specify the desired value that we want to query for. This guide aims to provide readers with different ways and examples for the same to query for is not null values in MongoDB.

How do I add a field in MongoDB?

To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .


2 Answers

In Mongoose, you can use a validator to check if a field has been set before you save it. As far as I know, there is no way of specifying on a Schema that a field is required, so it requires a little more boilerplate code.

like image 164
Charles A Avatar answered Sep 20 '22 17:09

Charles A


For required fields use $AND in collection's 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/

like image 24
Alina_Lapina Avatar answered Sep 17 '22 17:09

Alina_Lapina