Skip to content

Mongoose

CRUD and Validation

save, find, update, required fields, and where validation actually runs.

IntermediateAbout 6 minutes

Reads look like the driver: User.find({ city: "Bangalore" }). Writes split: `save()` on a document runs validators; `updateOne` / `findByIdAndUpdate` do not, unless you pass { runValidators: true }. That is the interview trap.

const rahul = new User({ name: "Rahul", email: "rahul@example.com" });
await rahul.save();

const users = await User.find({ city: "Bangalore" }).limit(20);
const one = await User.findById(id); // null if missing
Validation on save. Miss city → ValidationError.
await User.updateOne({ email: "rahul@example.com" }, { $set: { city: "Pune" } });

await User.findByIdAndUpdate(id, { status: "nope" }); // order enum not checked

await User.findByIdAndUpdate(id, { city: "Pune" }, { runValidators: true, new: true });
This skips required/enum unless runValidators

new: true returns the document after the update (driver returnDocument: 'after'). updateOne returns a result object, not a document. Casting: find({ age: "28" }) may cast to Number — convenient until it hides a type bug. Duplicate email is still 11000 from the unique index. Prefer $inc via updateOne for stock; findOne → change → save() is the race from Concurrency.

Interview question

Does Mongoose validate on updateOne and findByIdAndUpdate?

Think about it first.

Practice

The filter is the same; in Mongoose it is User.find(...).