Documents with Defaults and Required causes error on save

9 views
Skip to first unread message

Kirk Sefchik

unread,
Jun 20, 2017, 3:28:01 PM6/20/17
to Mongoose Node.JS ODM
When I set both default and required on a schema, saving a model causes an error if the model was instantiated using default values. 

For example: 
const Todo = new Schema({
  text
: {
    type
: String,
    required
: true,
   
default: '',
 
},
 
done: {
    type
: Boolean,
    required
: true,
   
default: false,
 
},
});

export default mongoose.model('Todo', Todo);

Later...
  new Todo()
 
.save()
 
.then(newTodo => res.json(newTodo))
 
.catch(e => res.status(500).send(e));

Causes this error to be thrown:
{
   
"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"
}

Additionally, I can inspect the value of the created todo before I save it and I can see that it's properly populating. However Mongoose still won't let me save. :(\
  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?



Reply all
Reply to author
Forward
0 new messages