Reputation: 178
This is my Schema and the image default
value doesn't seem to work when I leave the HTML input field empty before submitting a "blog" post.
var blogSchema = new mongoose.Schema({
title: String,
image: {
type: String,
default: "some image url"
},
body: String,
created: {
type: Date,
default: Date.now
}
});
this is the input that is going into the database.
{ __v: 0,
title: '',
body: '',
_id: 583af591c460fca539b8f787,
created: 2016-11-27T15:02:41.613Z,
image: '' }
I don't understand what the problem is since the image
doesnt have any value and it isn't setting the default value.
Upvotes: 2
Views: 5196
Reputation: 63
Official document says: "Note: Mongoose only applies a default if the value of the path is strictly undefined."
Here is the reference https://mongoosejs.com/docs/defaults.html
Upvotes: 0
Reputation: 1268
I had a similar difficulty and I opted for using a variable with a default value. It will be included when you are attempting to do the POST request.
var image = req.body.image || "some default value";
That assuming the user hasn't input anything, which makes its value null by default when the data is send to the backend.
Upvotes: 0
Reputation: 11
I solved this by adding an if statement as follows:
if(image === '') {
image = undefined;
}
Upvotes: 1
Reputation: 662
To clean out empty strings and anything else you think you don't want. Maybe try this lodash function before passing the object to mongo.
_.pickBy(updateObject, v => v !== null && v !== undefined && v !== ""); // removes all null, undefined and empty string values
Upvotes: 0