- Advanced Node.js Development
- Andrew Mead
- 243字
- 2021-08-27 19:06:02
Mongoose defaults
For completed, we're not going to require it because the completed value is most likely going to default to false. What we can do instead is set the default property, giving this completed field a default value.
completed: { type: Boolean, default: false },
Now completed, as we talked about earlier in the section, should default to false. There's no reason to create a Todo if it's already done. We can do the same thing for completedAt. If a Todo starts off not completed, then completedAt is not going to exist. It is only going to exist when the Todo has been completed; it's going to be that timestamp. What I'm going to do is set default equal to null:
completed: { type: Boolean, default: false }, completedAt: { type: Number, default: null }
Awesome. Now, we have a pretty good schema for our Todo. We're going to validate that the text is set up properly by the user, and we are going to set up the completed and completedAt values by our-self since we can just use defaults. With this in place, I can now rerun our server file, and here we get a better default Todo:
We have the text property and the user provided, which has been validated and trimmed. Next, we have completed set to false and completedAt set to null; this is fantastic. We now have a foolproof schema that has good defaults and validation.