Creating an instance of Mongoose model
Inside server.js, let's make a variable called todo to do what we've done previously, creating an instance of a Mongoose model. We're going to set it equal to new Todo, passing in our object and passing in the values we want to set. In this case, we just want to set text. We're going to set text to req.body, which is the object we have, and then we're going to access the text property, like so:
app.post('/todos', (req, res) => { var todo = new Todo({ text: req.body.text });
Next up, we're going to call todo.save. This is going to actually save the model to the database, and we're going to be providing a callback for a success case and an error case.
app.post('/todos', (req, res) => {
var todo = new Todo({
text: req.body.text
});
todo.save().then((doc) => { }, (e) => { });
Now if things go well, we're going to be sending back the actual Todo which is going to show up in the then callback. I'm going to get the doc, and right inside of the callback function, I'm going to use res.send to send the doc back. This is going to give the User really important information, things like the ID and the completed and completedAt properties, which were not set by the User. If things go poorly and we get an error, that's fine too. All we're going to do is use res.send to send that error back:
todo.save().then((doc) => { res.send(doc); }, (e) => { res.send(e); });
We'll be modifying how we send errors back a little later. For now, this code is going to work just great. We can also set an HTTP status.