MongoDB ~ Mongoose - rohit120582sharma/Documentation GitHub Wiki

Mongoose is an "Object Data Modeling" (ODM) library for MongoDB and Node.js.

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

The core concepts are that we work with schemas and models where we define how our data should look like.

A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document with type casting, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Mongoose Architecture


Getting Started

  1. First start the MongoDB server on a local machine

  2. Next install Mongoose library

$ npm install mongoose --save
  1. Next include mongoose in the project and open a connection to the database
const mongoose = require('mongoose');

const PROTOCOL = 'mongodb';
const HOST = 'localhost';
const PORT = 27017;
const DB_NAME = 'blog';
const URL = `${PROTOCOL}://${HOST}:${PORT}/${DB_NAME}`;

mongoose.connect(URL, {useNewUrlParser: true})
    .then(() => {
        console.log('Connected to MongoDB...');
        // now start the web server
    })
    .catch((e) => {
        console.error('FATAL ERROR: could not connect to MongoDB server...');
        console.error(e);
    });


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