How do I update a document in MongoDB with Mongoose?
User.findByIdAndUpdate(id, { name: 'new' }, { new: true }) updates and returns the updated document. Use { new: true } to get the updated document back, not the original. Or use updateOne for updates without fetching first.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Perform CRUD Operations With MongoDB and Node.js
Create with Model.create or save, read with find/findOne/findById, update with findByIdAndUpdate or updateOne, delete with findByIdAndDelete or deleteOne. Use query operators for filtering and pagination for large datasets.
Use User.create({ name, email }) or create a new instance and save: const user = new User(data); await user.save(). Both create a new document. User.create is a convenience that does both in one step.
User.find() returns all, User.findOne({ email }) returns one by query, User.findById(id) returns one by id. Use query operators like $gt, $lt, $in, $and, $or for filtering: User.find({ age: { $gt: 18 } }).
Still have questions?
Browse all our FAQs or reach out to our support team
