tareq3
12/7/2018 - 10:25 AM

MongoDb

Mongo Db with cli cmd

MongoDb is a document database or nosql database with no relation like firebase db

Install Mongodb and mongodb compass app

add the mongod path into environment variables

cheack mongo db version

mongod --version

Now you need to add the default directory for mongod

mkdir c:/dir
mkdir c:/dir/db

open mongo shell

mongo

show mongo databases in shell

show dbs

use db

use db-name

Run Mongodb server

mongod

server will open in:

localhost:27017

install mongoose on any project

npm i mongoose

import mongoose in project

const mongoose = require("mongoose");

create mongodb database and connect to the database

mongoose
    .connect("mongodb://localhost/playground", {
        useNewUrlParser: true
    })
    .then(() => console.log("Connect to mongo db..."))
    .catch(err => console.error("could not connect to mongo db ", err));

NOTE: Database won't be visible until any data inserted into database

For creating any data table in Nosql what is called as Schema


const course_Schema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: {
    type: Date,
    default: Date.now
  },
  isPublished: Boolean
});

We need to create a data model of the table/schema

const Course = mongoose.model("Course", course_Schema); //Course + s is the collection/table name 

For Inserting any data into table using Async funtion and await

async function createCourse(_name, _author, _tags, _isPublished) {
  const course = new Course({
    name: _name,
    author: _author,
    tags: _tags,
    isPublished: _isPublished
  });

  const result = await course.save();
  console.log(result);
}

calling the function

createCourse("node", "Mosh", ["node", "rest"], true);