MyInternships.in

Databases & Data Access

Node.js MongoDB CRUD Operations

Mongoose exposes create, read, update and delete through model methods. Every one returns a thenable query, so they work naturally with async/await.


What is MongoDB CRUD Operations in Node.js?

Mongoose exposes create, read, update and delete through model methods. Every one returns a thenable query, so they work naturally with async/await.

MongoDB CRUD Operations example

The full set
JavaScript
// CREATE
const job = await Job.create({ title: 'Frontend Intern', company: 'Zoho' });

// READ
const all      = await Job.find({ status: 'active' }).limit(20).lean();
const one      = await Job.findById(id);
const byFilter = await Job.findOne({ company: 'Zoho' });
const count    = await Job.countDocuments({ city: 'Pune' });

// UPDATE — new: true returns the updated document
const updated = await Job.findByIdAndUpdate(id, { stipend: 20000 }, {
  new: true,
  runValidators: true,
});

// DELETE
await Job.findByIdAndDelete(id);
await Job.deleteMany({ status: 'closed' });

Key points to remember

  • Without new: true, findByIdAndUpdate returns the document as it was before.
  • runValidators: true is required — update operations skip schema validation by default.
  • select() limits returned fields and reduces network transfer.
  • An invalid ObjectId string throws a CastError — validate it before querying.

Common mistakes with MongoDB CRUD Operations

  • Assuming findByIdAndUpdate validates — it does not unless you ask.
  • Passing an unvalidated id and getting an unhandled CastError.
  • Using find() without a limit on a large collection.

Node.js MongoDB CRUD Operations— Interview Questions & FAQs

Why does findByIdAndUpdate return the old document?+

That is the default. Pass { new: true } to get the document after the update is applied.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships