Performance: Updating documents
This affects server response time and client perceived latency when updating data that triggers UI changes.
Jump into concepts and practice - no test required
app.put('/item/:id', async (req, res) => { const id = req.params.id; const update = req.body; const result = await db.collection('items').findOneAndUpdate( {_id: new ObjectId(id)}, {$set: update}, {returnDocument: 'after'} ); res.send(result.value); });
app.put('/item/:id', async (req, res) => { const id = req.params.id; const update = req.body; const doc = await db.collection('items').findOne({_id: new ObjectId(id)}); Object.assign(doc, update); await db.collection('items').updateOne({_id: new ObjectId(id)}, {$set: doc}); res.send(doc); });
| Pattern | DB Calls | Server Delay | Network Payload | Verdict |
|---|---|---|---|---|
| Fetch then update | 2 calls (findOne + updateOne) | High (extra 50-100ms) | Larger (full doc sent back) | [X] Bad |
| Atomic findOneAndUpdate | 1 call | Low (minimal delay) | Smaller (only updated doc) | [OK] Good |
findByIdAndUpdate method do in Express with Mongoose?findByIdAndUpdate is used to find a document by its ID and update it with new data.{ new: true }, it returns the updated document, not the old one.findByIdAndUpdate with parameters: id, update object, options, and callback.{ new: true } ensures the updated document is returned.Model.findByIdAndUpdate('123', { name: 'Alice' }, { new: true }, (err, doc) => {
if (err) return console.error(err);
console.log(doc.name);
});{ new: true } returns the updated document.doc.name, which will be 'Alice' after update.Model.findByIdAndUpdate('123', { age: 30 }, (err, doc) => {
if (err) console.log(err);
else console.log(doc);
});findByIdAndUpdate is correct and callback parameters are valid.{ new: true }, the returned document is the old one, not updated.{ new: true } to get the updated document.