default
and required
on a schema, saving a model causes an error if the model was instantiated using default values. const Todo = new Schema({
text: {
type: String,
required: true,
default: '',
},
done: {
type: Boolean,
required: true,
default: false,
},
});
export default mongoose.model('Todo', Todo);
new Todo()
.save()
.then(newTodo => res.json(newTodo))
.catch(e => res.status(500).send(e));
{
"errors": {
"text": {
"message": "Path `text` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "text",
"value": ""
},
"kind": "required",
"path": "text",
"value": ""
}
},
"_message": "Todo validation failed",
"name": "ValidationError"
}
let todo = new Todo();
console.log(todo.inspect());
// { _id: 594972eefe0b873338fe939d, done: false, text: '' }
// It's populated! Why won't it save?
todo
.save()
.then(newTodo => res.json(newTodo))
.catch(e => res.status(500).send(e));
TBH, this looks like a bug to me. There might be a way to do this that I'm not seeing... Anyone have any thoughts on how I can make this `save()` call work with default data?