PATCH request gives 200 but not updating database (MongoDB)
I spent hours debugging a PATCH request that looked perfect but was not updating the database. this is the code
app.patch(async (req, res) => {
let user = await User.findById(req.params.id);
if(!user){
return res.status(404).json({ message: "user not found"});
}
Object.assign(user, req.body);
await user.save();
return res.status(200).json({
user,
message: "user updated successfully"
})
})
i was sending the PATCH request from Postman using the key as last_name but mongoose schema has the key as lastName.
So the request was sent and i recieved a status 200 (All OK) but the field was not updating in the database.
then i debugged it for nearly 1-1.5 hours and got frustated then i opened postman and thought that let's change the key name and try it. and it worked!!!
i was using last_name (snake case) instead of lastName (camel case) because before using mongodb, i was using file system to store the data in memory and the field there was last_name.
but due to this i learnt a new thing about mongoose.
Here is my learning:
Mongoose documents are not just plain JS objects. They are special instances of a model.
When we use Object.assign(user, req.body) or user.set(req.body), then mongoose runs a process called "Internal Mapping"
here is how mongoose do this:
- It loops through the keys in req.body
- It checks if the key exists in our new mongoose.Schema({...})
- If it exists: It updates the value
- If it does not exists: It silently drops the key to prevent polluting your database with random data.
Best practices to follow so that we don't get into this mess:
- Always pick a standard (for e.g. use camalCase for everything or you can choose your own as well)
- Validation (extra safe): we can also add runValidators: true to our update calls to ensure new data still follows our schema rules (for e.g., unique: true for emails)
- Logging: always keep a console.log(req.body) at the top of your route while developing the backend. if you see the data in the console but not in the database then it's always a mismatch in the naming (like in my case: last_name and lastName)
Comments
Join the discussionNo comments yet. Be the first to comment.
