← Back to all tutorials

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

OptionDefaultPurpose
new: truefalseReturn the updated document (not the original)
runValidators: truefalseRun schema validators on the updated data
upsert: truefalseCreate the document if it does not exist
overwrite: truefalseReplace 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

AspectPUTPATCH
IntentReplace the entire resourcePartially update specific fields
Mongoose methodfindByIdAndUpdate with overwrite: truefindByIdAndUpdate (default behavior)
Missing fieldsShould be set to defaults/nullLeft 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: true to get the updated document and runValidators: true to enforce schema validation
  • Check for null return to handle non-existent documents with a 404 response
  • Mongoose's default update behavior is partial (PATCH-like) — use overwrite: true for strict PUT