Referenced from This particular tutorial on MERN stack development...
In my mongoose schema, I have defined 4 fields:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: false
},
comments: {
type: String,
required: false
},
done: {
type: Boolean,
required: true
},
});
module.exports = mongoose.model('Todo', Todo);
I'm using the update
route as follows:
todoRoutes.route('/update/:id').post(function(req, res) {
Todo.findByIdAndUpdate(req.params.id, req.body, function(err, todo) {
if (err)
res.status(400).send('Updating item failed: ' + err);
else
todo.save().then(todo => {
res.json('Item updated!');
}).catch(err => {
res.status(400).send("Update not possible: " + err);
});
});
});
When sending the following body to the route:
{
"name": "bla"
}
An "ok" status is returned, and the document is successfully updated. However, when adding an extra field like this:
{
"name": "bla",
"unwanted_field": true
}
- The additional field does not show in the database retrieval although it still returns without error. Why is this happening?
- Why does the update operation not enforce the "required" fields and allows any updates to go through?