Episode 13 of 17
PUT Requests
Implement the PUT endpoint — find a document by ID and update it in MongoDB using findByIdAndUpdate with validation.
PUT Requests
PUT requests update an existing resource. In this episode you will implement the PUT endpoint using Mongoose's findByIdAndUpdate() method to modify ninja documents in MongoDB.
The PUT Route
router.put('/:id', async (req, res, next) => {
try {
const ninja = await Ninja.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true,
}
);
if (!ninja) {
return res.status(404).json({ error: 'Ninja not found' });
}
res.json(ninja);
} catch (err) {
next(err);
}
});
findByIdAndUpdate Options
| Option | Default | Purpose |
|---|---|---|
new: true | false | Return the updated document (not the original) |
runValidators: true | false | Run schema validators on the updated data |
upsert: true | false | Create the document if it does not exist |
overwrite: true | false | Replace the entire document (true PUT behavior) |
Without new: true, Mongoose returns the document as it was before the update. Without runValidators: true, invalid data can bypass your schema validation.
Testing with Postman
PUT http://localhost:3000/api/ninjas/65a1b2c3d4e5f6a7b8c9d0e1
Body:
{
"name": "Ryu",
"rank": 8,
"available": true
}
Response: 200 OK
{
"_id": "65a1b2c3d4e5f6a7b8c9d0e1",
"name": "Ryu",
"rank": 8,
"available": true,
"updatedAt": "2024-01-15T12:00:00.000Z"
}
PUT vs PATCH in Mongoose
| Aspect | PUT | PATCH |
|---|---|---|
| Intent | Replace the entire resource | Partially update specific fields |
| Mongoose method | findByIdAndUpdate with overwrite: true | findByIdAndUpdate (default behavior) |
| Missing fields | Should be set to defaults/null | Left unchanged |
In practice, many APIs use findByIdAndUpdate for both PUT and PATCH. The default behavior of findByIdAndUpdate is actually a partial update (PATCH-like). For strict PUT behavior that replaces the entire document, add overwrite: true.
Key Takeaways
findByIdAndUpdate()finds and updates a document in one operation- Always use
new: trueto get the updated document andrunValidators: trueto enforce schema validation - Check for
nullreturn to handle non-existent documents with a 404 response - Mongoose's default update behavior is partial (PATCH-like) — use
overwrite: truefor strict PUT