DEV Community

Yeasin Arafat
Yeasin Arafat

Posted on

What is Mongoose? How does it work with CRUD Operations?

It manages relationship data, provides schema validation, and translates between objects in code and the representation of those objects in MongoDB. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
Documents
‘Documents’ are equivalent to records or rows of data in SQL. While a SQL row can reference data in other tables, Mongo documents usually combine that in a document
Fields
‘Fields’ or attributes are similar to columns in a SQL table.
Schema
Mongoose ‘schema’ is a document data structure (or shape of the document) that is enforced via the application layer.

Mongoose Model vs Schema
A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
Creating a Mongoose model comprises primarily of three parts: Referencing Mongoose, Defining the Schema, Exporting a Model

CRUD Operations
Mongoose has a flexible API and provides many ways to accomplish a task. We will not focus on the variations because that is out of scope for this article, but remember that most of the operations can be done in more than one way either syntactically or via the application architecture.
Create Record
let EmailModel = require('./email')

let msg = new EmailModel({
email: 'ADA.LOVELACE@GMAIL.COM'
})

msg.save()
.then(doc => {
console.log(doc)
})
.catch(err => {
console.error(err)
})
output:
{
_id: 5a78fe3e2f44ba8f85a2409a,
email: 'ada.lovelace@gmail.com',
__v: 0
}
Following rules:
The _id field is auto-generated by Mongo and is a primary key of the collection. Its value is a unique identifier for the document.
The value of the email field is returned. Notice that it is lower-cased because we specified the lowercase:true attribute in the schema.
__v is the versionKey property set on each document when first created by Mongoose. Its value contains the internal revision of the document.

Fetch Record
Let’s try to retrieve the record we saved to the database earlier. The model class exposes several static and instance methods to perform operations on the database. We will now try to find the record that we created previously using the find method and pass the email as the search term.
EmailModel
.find({
email: 'ada.lovelace@gmail.com' // search query
})
.then(doc => {
console.log(doc)
})
.catch(err => {
console.error(err)
})

Update Record
Let’s modify the record above by changing the email address and adding another field to it, all in a single operation. For performance reasons, Mongoose won’t return the updated document so we need to pass an additional parameter to ask for it:
EmailModel
.findOneAndUpdate(
{
email: 'ada.lovelace@gmail.com' // search query
},
{
email: 'theoutlander@live.com' // field:values to update
},
{
new: true, // return updated doc
runValidators: true // validate before update
})
.then(doc => {
console.log(doc)
})
.catch(err => {
console.error(err)
})
updated email like:
{
_id: 5a78fe3e2f44ba8f85a2409a,
email: 'theoutlander@live.com',
__v: 0
}
Delete Record
We will use the findOneAndRemove call to delete a record. It returns the original document that was removed:
EmailModel
.findOneAndRemove({
email: 'theoutlander@live.com'
})
.then(response => {
console.log(response)
})
.catch(err => {
console.error(err)
})

Top comments (0)