Skip to main content

Operations (CRUD) Reference

Once again, we will be discussing the four major operations typically performed on data: Create, Read, Update and Delete (CRUD). The operations in the code below will each work with the familiar "companySchema" using the "Company" model:

let companySchema = new Schema({
companyName: String,
address: String,
phone: String,
employeeCount: {
type: Number,
default: 0,
},
country: String,
});

let Company = mongoose.model('companies', companySchema);

Create

To "save" (create) a new document, we must first create the document in code using the model we want (ie: "Company"). Then we can call a built in method, "save" on the new object to save it.

const kwikEMart = new Company({ ... });

kwikEMart.save().then(() => {
// everything good
console.log("kwikEMart saved");
}).catch(err => {
// there was an error
console.log(err);
});

Read

To "find" (read) documents from the database, we use the "find" method on the model object itself (ie: "Company"), ie:

Company.find({ companyName: 'The Kwik-E-Mart' })
//.sort({}) //optional "sort" - https://docs.mongodb.com/manual/reference/operator/aggregation/sort/
.exec()
.then((companies) => {
// companies will be an array of objects.
// Each object will represent a document that matched the query
console.log(companies);
});

Selecting specific fields

If we wish to limit the results to include only specific fields, we can pass the list of fields as a space-separated string in the second parameter to the find() method, ie:

Company.find({ companyName: 'The Kwik-E-Mart' }, 'address phone')
//.sort({}) //optional "sort" - https://docs.mongodb.com/manual/reference/operator/aggregation/sort/
.exec()
.then((companies) => {
// companies will be an array of objects.
// Each object will represent a document that matched the query
console.log(companies);
});

For complex queries (ie: "greater than", "in", "or", etc, etc.) see the Mongoose Query Guide and the MongoDB documentation under Query and Projection Operators

Update

To update documents in the database, we use the updateOne() / updateMany() methods on the model object (ie: "Company"). We typically pass these function two arguments: the query to select which documents to update and the fields to set for the documents that match the query.

NOTE: See update operators, ie: $set, $push and $addToSet for more information.

Company.updateOne( { companyName: 'The Kwik-E-Mart' }, { $set: { employeeCount: 3 } })
.exec()
.then(() => {
// updated company
console.log('updated company');
})
.catch((err) => {
console.log(err);
});

Delete

To delete documents in the database, we use the deleteOne() / deleteMany() methods on the model object (ie: "Company").

Company.deleteOne({ companyName: 'The Kwik-E-Mart' })
.exec()
.then(() => {
// removed company
console.log('removed company');
})
.catch((err) => {
console.log(err);
});