Hint: Add { new: true } to get updated document in callback [OK]
Common Mistakes:
Assuming updateById is a valid method
Expecting updated doc without { new: true }
Thinking update object must be string
5. You want to update a user's email only if the new email is not empty and valid. Which approach correctly updates the document safely in Express with Mongoose?
hard
A. Check email validity before calling findByIdAndUpdate, then update with { new: true } option.
B. Call findByIdAndUpdate directly without validation to save time.
C. Use findByIdAndUpdate with an empty update object if email is invalid.
D. Update the document without callback and ignore errors.
Solution
Step 1: Validate input before updating
Always check if the new email is valid and not empty before updating to avoid bad data.
Step 2: Use findByIdAndUpdate with { new: true }
Update the document with the valid email and use { new: true } to get the updated document.
Final Answer:
Check email validity before calling findByIdAndUpdate, then update with { new: true } option. -> Option A
Quick Check:
Validate input + update with new:true = A [OK]
Hint: Always validate input before updating documents [OK]