22

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.

Joseph T F
  • 801
  • 1
  • 7
  • 19

2 Answers2

54

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

Joschua Schneider
  • 3,703
  • 1
  • 15
  • 18
  • 1
    i was trying with the wrong command optional:' '. Not sure from where i got that. Anyways this is working thanks for the help. :) – Joseph T F Dec 15 '16 at 06:02
  • 1
    upvote for the answer !! but please look into few conditions it does have as it seems to work on new inserts only unless you specify to work on updates as well, check these : (https://mongoosejs.com/docs/defaults.html) or (https://stackoverflow.com/questions/57433942/how-can-i-use-partialfilterexpression-on-a-mongoose-model/57434190#57434190) – whoami - fakeFaceTrueSoul Aug 09 '19 at 17:05
1

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.

CyberMessiah
  • 1,084
  • 11
  • 14