Performance: Resource ownership checks
This affects server response time and user interaction speed by adding authorization logic before resource access.
app.get('/resource/:id', async (req, res) => { const resource = await Resource.findOne({ _id: req.params.id, ownerId: req.user.id }).select('_id data'); if (!resource) return res.status(404).send('Not found or no access'); res.send(resource); });
app.get('/resource/:id', async (req, res) => { const resource = await Resource.findById(req.params.id); if (!resource) return res.status(404).send('Not found'); if (resource.ownerId.toString() !== req.user.id) return res.status(403).send('Forbidden'); res.send(resource); });
| Pattern | DB Query Cost | Data Transferred | Response Time Impact | Verdict |
|---|---|---|---|---|
| Fetch full resource then check ownership | High (full document fetch) | Large (all fields) | Slower (blocks response) | [X] Bad |
| Query with ownership filter and select fields | Low (filtered query) | Small (selected fields) | Faster (quick response) | [OK] Good |
| Middleware full fetch for ownership | High (full fetch every request) | Large | Slower (adds latency) | [X] Bad |
| Middleware existence check with ownership filter | Low (exists query) | Minimal | Faster (lightweight check) | [OK] Good |
req.params.id and owner ID in resource.ownerId?req.user.id with resource.ownerId using strict equality to confirm ownership.req.user.id is '123' and resource.ownerId is '456'?
app.delete('/items/:id', (req, res) => {
const resource = {ownerId: '456'};
if (req.user.id === resource.ownerId) {
res.send('Deleted');
} else {
res.status(403).send('Forbidden');
}
});req.user.id ('123') does not equal resource.ownerId ('456'), ownership check fails.function checkOwnership(req, res, next) {
const resource = {ownerId: '456'}; /* example */
if (req.user.id = resource.ownerId) {
next();
} else {
res.status(403).send('Forbidden');
}
}req.user.id and resource.ownerId.post.ownerId. Which Express middleware correctly implements this ownership check and returns 403 if the user is not the owner?req.user.id matches post.ownerId and calls next() if true.Pass the test and this pattern moves unknown