Skip to content

Instantly share code, notes, and snippets.

@tareq3
Last active December 13, 2018 17:33
Show Gist options
  • Save tareq3/535c2029812da08fd7cec7ddaa058d05 to your computer and use it in GitHub Desktop.
Save tareq3/535c2029812da08fd7cec7ddaa058d05 to your computer and use it in GitHub Desktop.
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);
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment