Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make all fields required in Mongoose

Mongoose seems to default to make all fields not required. Is there any way to make all the fields required without changing each of:

Dimension = mongoose.Schema(
  name: String
  value: String
)

to

Dimension = mongoose.Schema(
  name:
    type: String
    required: true
  value: 
    type: String
    required: true
)

It'll get really ugly since I have a lot of these.

like image 248
maxko87 Avatar asked Nov 04 '13 05:11

maxko87


People also ask

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

What does save () do in mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What does trim do in mongoose?

Definition. Removes whitespace characters, including null, or the specified characters from the beginning and end of a string. The string to trim.


2 Answers

I ended up doing this:

r_string = 
  type: String
  required: true 

r_number = 
  type: Number
  required: true

and on for the other data types.

like image 156
maxko87 Avatar answered Oct 11 '22 11:10

maxko87


You could do something like:

var schema = {
  name: { type: String},
  value: { type: String}
};

var requiredAttrs = ['name', 'value'];

for (attr in requiredAttrs) { schema[attr].required = true; }

var Dimension = mongoose.schema(schema);

or for all attrs (using underscore, which is awesome):

var schema = {
  name: { type: String},
  value: { type: String}
};

_.each(_.keys(schema), function (attr) { schema[attr].required = true; });

var Dimension = mongoose.schema(schema);
like image 45
190290000 Ruble Man Avatar answered Oct 11 '22 10:10

190290000 Ruble Man