Introduction to Mongoose for MongoDB | Divyansh Rai

Post

editor-img
Divyansh Rai
Oct 20, 2022

Introduction to Mongoose for MongoDB

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data,

media

provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

Getting Started

Mongo Installation

Download the appropriate MongoDB version for your Operating System from the MongoDB Website and follow their installation instructions

Database Connection:

Create a file ./src/database.js under the project root.

let mongoose = require('mongoose');const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVERconst database = 'fcc-Mail'; // REPLACE WITH YOUR DB NAMEclass Database { constructor() { this._connect() }_connect() { mongoose.connect(`mongodb://${server}/${database}`) .then(() => { console.log('Database connection successful') }) .catch(err => { console.error('Database connection error') }) }}module.exports = new Database()

The require(‘mongoose’) call above returns a Singleton object. It means that the first time you call require(‘mongoose’), it is creating an instance of the Mongoose class and returning it. On subsequent calls, it will return the same instance that was created and returned to you the first time because of how module import/export works in ES6.

media

Basic Operations

Create email Model:

let mongoose = require('mongoose')let validator = require('validator')let emailSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, lowercase: true, validate: (value) => { return validator.isEmail(value) } }})module.exports = mongoose.model('Email', emailSchema)

Let’s create an instance of the email model and save it to the database:

let EmailModel = require('./email')let msg = new EmailModel({ email: 'divyanshrai27@gmail.com'})msg.save() .then(doc => { console.log(doc) }) .catch(err => { console.error(err) })

The result is a document that is returned upon a successful save:

{ _id: has03948ytoeirlu98345dsf, email: 'divyanshrai27@gmail.com', __v: 0 }

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: 'divyanshrai27@gmail.com' // search query }) .then(doc => { console.log(doc) }) .catch(err => { console.error(err) })

The document returned will be similar to what was displayed when we created the record:

{ _id: 5a78fe3e2f44ba8f85a2409a, email: 'divyanshrai27@gmail.com', __v: 0 }

Checkout related posts on: