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).
| Action | Mongoose method |
|---|---|
| Create | User.create({...}) |
| Read all | User.find() |
| Read one | User.findById(id) |
| Update | User.findByIdAndUpdate(id, {...}) |
| Delete | User.findByIdAndDelete(id) |
// 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.)
- Create —
User.create({...})saves a new document and returns it. - Read —
User.find()gets many,User.findById(id)gets one by its id. - Update —
User.findByIdAndUpdate(id, {...})changes fields on one document. - Delete —
User.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?
✍️ Practice
- Use a model to create a document, then find all documents.
- Update a document by id, then delete it.
🏠 Homework
- Write functions for all five CRUD operations on your
Productmodel.