Joseph T F
Joseph T F

Reputation: 801

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.

Upvotes: 22

Views: 64760

Answers (2)

Joschua Schneider
Joschua Schneider

Reputation: 4093

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

Upvotes: 56

CyberMessiah
CyberMessiah

Reputation: 1268

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.

Upvotes: 1

Related Questions