Recap
Recap

Reputation: 178

Why doesn't the `default` value work in mongoose schema when nothing was entered?

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

Answers (4)

Yusuf Alp
Yusuf Alp

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

CyberMessiah
CyberMessiah

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

Andy Hall
Andy Hall

Reputation: 11

I solved this by adding an if statement as follows:

if(image === '') {
  image = undefined;
}

Upvotes: 1

Thunder Cat King
Thunder Cat King

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

Related Questions