Mongoose & the Full StackCore· 40 min read

CRUD with Mongoose

Create, read, update and delete documents from your Node code using model methods.

What you will learn

  • Create and read with model methods
  • Update and delete documents
  • Use async/await with Mongoose

Model methods = CRUD

Mongoose models give you async methods for every operation. Use await inside async functions (wrapped in try/catch).

ActionMongoose method
CreateUser.create({...})
Read allUser.find()
Read oneUser.findById(id)
UpdateUser.findByIdAndUpdate(id, {...})
DeleteUser.findByIdAndDelete(id)
Full CRUD with a Mongoose model
// Create
const user = await User.create({ name: "Asha", email: "asha@x.com" });

// Read
const all = await User.find();
const one = await User.findById(someId);

// Update
await User.findByIdAndUpdate(someId, { age: 23 });

// Delete
await User.findByIdAndDelete(someId);

Notice await in front of every call — these talk to the database, which takes time, so you wait for the result. User.create({...}) makes and saves a new document and hands it back (now with an _id). User.find() returns an array of all users, while User.findById(someId) returns the single user with that id. findByIdAndUpdate(someId, { age: 23 }) finds that user and changes the given fields, and findByIdAndDelete(someId) finds and removes that user.

Note: Output (the value of user after create): { id: ObjectId('65f...a1'), name: 'Asha', email: 'asha@x.com', _v: 0 } Mongoose returns the saved document, including the _id it generated. (__v is just an internal version counter Mongoose adds — you can ignore it.)

  1. CreateUser.create({...}) saves a new document and returns it.
  2. ReadUser.find() gets many, User.findById(id) gets one by its id.
  3. UpdateUser.findByIdAndUpdate(id, {...}) changes fields on one document.
  4. DeleteUser.findByIdAndDelete(id) removes one document by its id.

Tip: These methods return promises, so always await them inside an async function and wrap risky calls in try/catch — exactly the async pattern you learned in JavaScript and Node.

Q. Which Mongoose method creates a new document?

Answer: User.create({...}) builds and saves a new document. find/findById read, findByIdAndUpdate updates, findByIdAndDelete removes.

✍️ Practice

  1. Use a model to create a document, then find all documents.
  2. Update a document by id, then delete it.

🏠 Homework

  1. Write functions for all five CRUD operations on your Product model.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →