Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make mongoose string schema type default value as blank and make the field optional

I have a test schema with mongoose in nodejs like

testschema = mongoose.Schema({
         name:{
    type:String,
    required:true,
    unique:true
  },
  image:{
    type:String,
    required:true
  },
  category:{
    type:String
  },
});

How can i make the category field as optional and make it default to blank if not given by user?

I tried

 category:{
        type:String,
        optional: ''
      },

but when printing out the documents saved with the scheme it doesnt even shows the field category.

like image 462
Joseph T F Avatar asked Dec 08 '16 07:12

Joseph T F


2 Answers

What you most likely need here is to set the default value.

category: {
    type: String,
    default: ''
}

This makes the field somewhat optional, because if you don't set it, it defaults to ''

Additionally, you can pass a function to generate a default value:

date: {
    type: Date,
    default: Date.now
}

Note that we are passing Date.now here (not Date.now()), which is a function that returns the current timestamp. This is equivalent to an arrow function like:

default: () => Date.now()

Setting defaults on Update

As mentioned by user whoami, mongoose only sets defaults on insert.

If you are using mongoose 4.x and up and MongoDB 2.4.0 and up you can opt-in to setting default values on update too.

All update and findOneAndUpdate queries also apply defaults when setting the upsert flag.

Mongoose docs: The setDefaultsOnInsert option

like image 145
Joschua Schneider Avatar answered Sep 28 '22 21:09

Joschua Schneider


Another way to overcome this current limitation on the new inserts is just to place a default value when you are doing the post request. As in this sample code:

var category = req.body.category || 0;

That assuming the user hasn't touched the field, therefore its value is null by default.

like image 35
CyberMessiah Avatar answered Sep 28 '22 21:09

CyberMessiah