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.
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()
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With