Mongoose ~ CRUD Operations - rohit120582sharma/Documentation GitHub Wiki

Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose Query object.

Mongoose will execute the query asynchronously and return a promise.

Saving a document

let author = new Author({ name: '' });
author = await author.save();

Querying documents

const courses = await Course
    .find({ author: ‘Mosh’, isPublished: true })
    .skip(10)
    .limit(10)
    .sort({ name: 1, price: -1 })
    .select({ name: 1, price: 1 });

Updating a document (query first)

const course = await Course.findById(id);
if (!course) return;
course.set({ name: ... });
course.save();

Updating a document (update first)

const result = await Course.update(
    { _id: id },
    { $set: { name: ... }}
);

Updating a document (update first) and return it

const result = await Course.findByIdAndUpdate(
    { _id: id },
    { $set: { name: ... }},
    { new: true }
);

Removing a document

const result = await Course.deleteOne({ _id: id });
const result = await Course.deleteMany({ _id: id });
const course = await Course.findByIdAndRemove(id);


⚠️ **GitHub.com Fallback** ⚠️