Mongoose Basic Explanation of follow as below
Starting with Mongoose
Q. why I use mongoose
Q. difference mongoose and mongo
Q. what is schema
Schema is a kind of an index of the data type that we're going to
working with
.................................................................................................................................................................................................................................
. IDE
. Node.js & NPM
. Mongo Database
. REST Client
. Robo 3T for MongoDB
............................................................................................................................................................................................................................
MongoDb
. Local Installation
. mLab Cloud
. Docker
............................................................................................................................................................................................................................
REST Client (Api Testing )
. Insomnia
. Postman
............................................................................................................................................................................................................................
Application Setup
Getting Started
. Project Folder
. Initialize Node.js Project
. Hello world
............................................................................................................................................................................................................................
npm init -y
or
npm init // yes or as per choice
yarn global add nodemon
yarn add express body-parser mongodb
yarn add nodemon
............................................................................................................................................................................................................................
project
............................................................................................................................................................................................................................
src/server.js
const express = require('express')
const app = express()
app.use(express.static('public'))
const port = process.env.PORT || 3000
app.listen(port, (req, res)=>{
console.log(`Server is running on Port ${port}`)
})
............................................................................................................................................................................................................................
public/index.htm
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1> Hello Express..... </h1>
</body>
</html>
............................................................................................................................................................................................................................
nodemon src/server
Server is running on Port 3000
............................................................................................................................................................................................................................
USING ROUTER
src/server.js
const express = require('express')
const app = express()
const routeperson = require('./routes/person')
app.use(routeperson)
app.use(express.static('public'))
const port = process.env.PORT || 3000
app.listen(port, (req, res)=>{
console.log(`Server is running on Port ${port}`)
})
............................................................................................................................................................................................................................
routes/person.js
const express = require('express')
const route = express.Router()
route.get('/', (req,res)=>{
res.send('you have request person')
})
module.exports = route
....................
using params .............
const express = require('express')
const route = express.Router()
route.get('/:name', (req,res)=>{
res.send(`you have request person ${req.
params.name}`)
})
module.exports = route
display out
http://localhost:3000/sapan
....................
using Query .............
const express = require('express')
const route = express.Router()
route.get('/', (req,res)=>{
if(req.
query.name){
res.send(`you have request person ${req.
query.name}`)
}
else{
res.send('you have request person')
}
})
module.exports = route
http://localhost:3000/?name=sapanss
............................................................................................................................................................................................................................
How to use different Static File
const express = require('express')
const app = express()
const path = require('path')
//const routeperson = require('./routes/person')
//app.use(routeperson)
//app.use(express.static('public'))
app.get('/', (req, res)=>{
res.sendFile(path.join(__dirname, '../public/500.html'))
})
const port = process.env.PORT || 3000
app.listen(port, (req, res)=>{
console.log(`Server is running on Port ${port}`)
})
............................................................................................................................................................................................................................
Express js using ES6
npm init
server/index.js
import express from 'express';
const app = express();
app.get('/', (req, res)=>{
res.send('Hello world ')
})
const port = process.env.PORT || 3000
app.listen(port, (req, res)=>{
console.log(`Server is running on port ${port}`)
})
.....................................................................................................
install
step -1
npm install --save-dev babel-cli
or
yarn add babel-cli
.......................................................................................................
step -2
open package.json
"server": "babel-node server/index.js"
note: server is folder only
or
"server":"nodemon --watch server --exec babel-node -- server/index.js"
or
"server": "nodemon --watch server --exec babel-node -- App/App.js",
or
"server":"nodemon --watch server --exec babel-node -- server/index.js",
Note : after the --watch this is server keyword is our real server do not haveany folder by name
.......................................................................................................
step -3
npm install --save-dev babel-preset-es2015
or
yarn add babel-preset-es2015
create a file with name .babelrc root dir
.babelrc
{
"presets":["es2015"]
}
......................................................................................................
step -4
npm run server
..............................................................................................................................................................................................................................................
Example # Express + Json
const express = require('express')
const router = express.Router()
const app = express()
const members =[{
id:1,
name:'Johan Doe',
email:'johan@gmail.com',
status:'active'
},{
id:2,
name:'Mika Doe',
email:'Mikadoe@gmail.com',
status:'inactive'
},{
id:3,
name:'Michkel ',
email:'michkel@gmail.com',
status:'inactive'
}]
app.get('/api/members', (req, res)=>{
res.json(members)
})
const port = process.env.PORT || 5000
app.use( router)
app.listen(port,()=>{
console.log(`Server is running on port ${port}`)
})
...........................................................................................................................................................................................................................................
OR
# server/Server.js
const express = require('express')
const router = express.Router()
const app = express()
const members = require('../Members.js')
app.get('/api/members', (req, res)=>{
res.json(members)
})
// Get Single Members
app.get('/api/members/:id', (req, res) => {
//res.json(members.filter(item=>item.id===parseInt(req.params.id)))
const found = members.some(member => member.id === parseInt(req.params.id));
if (found) {
res.json(members.filter(member => member.id === parseInt(req.params.id)))
}
else {
res.status(400).json({ message: `No member with the id of ${req.params.id}` })
}
})
//Create a Members
//yarn add uuid
router.post('/', (req, res)=>{
//res.send(req.body)
const newMembers ={
id:uuid.v4(),
name:req.body.name,
email:req.body.email,
status:'active'
};
if(!newMembers.name || !newMembers.email){
return res.status(400).json({message:'Please include email and name'})
}
members.push(newMembers)
res.json(members)
})
//update members
router.put('/:id', (req, res)=>{
const found =members.some(member=>member.id === parseInt(req.params.id));
if(found){
const updateMember = req.body
members.forEach(member=>{
if(member.id === parseInt(req.params.id)){
//member.name= req.body.name
// member.email =req.body.email
member.name= updateMember.name ? updateMember.name : member.name
member.email =updateMember.email ? updateMember.email : member.email
res.json({message: 'update successfully', member})
}
})
}
else{
res.status(400).json({message:`Hey, try again ${req.params.id}`})
}
})
//members deleted
router.delete('/:id', (req, res) => {
const found = members.some(member => member.id === parseInt(req.params.id));
if (found) {
res.json({
message:'Member deleted',
members:members.filter(member => member.id === parseInt(req.params.id))
})
}
else {
res.status(400).json({ message: `No member with the id of ${req.params.id}` })
}
})
const port = process.env.PORT || 5000
app.use( router)
app.listen(port,()=>{
console.log(`Server is running on port ${port}`)
})
# Members.js
const members =[{
id:1,
name:'Johan Doe',
email:'johan@gmail.com',
status:'active'
},{
id:2,
name:'Mika Doe',
email:'Mikadoe@gmail.com',
status:'inactive'
},{
id:3,
name:'Michkel ',
email:'michkel@gmail.com',
status:'inactive'
}]
module.exports =members
......................................................................................................................................................................................................................................
1. Install MongoDB
download mongodb using below the link
https://www.mongodb.com/download-center/community
or
https://www.mongodb.com/
or
install guidehttps://medium.com/@LondonAppBrewery/how-to-download-install-mongodb-on-windows-4ee4b3493514
product -->MongoDb Server
Start free with MongoDB Atlas
https://www.mongodb.com/download-center/communityor
Server--> Download
...................................................................................................................................................................................................................................
2.1 Mongodb commands
Note - First Go to C drive and open a under create a folder name with data and inside data folder create a another folder like db
like that C:\data\db
run the command (in mycase path is )
C:\Program Files\MongoDB\Server\4.2\bin\
C:\Program Files\MongoDB\Server\4.2\bin\>mongod
Note - Uses mongod to start MongoDB.
2.2 Connect MongoDB [ Note: - open a another terminal and follow bellow steps like that]
To connect MongoDB, uses
C:\Program Files\MongoDB\Server\4.2\bin\>mongo
check version
mongo --version
2.3 Three database commands you should know.
show dbs – List all databases.
use db_name – Switches to db_name.
show collections – List all tables in the current selected database.
Note - In MongoDB, collection means table in SQL.
show dbs
use mydb
db.books.insert({"name": "mongo book"})
db.books.insert({"name": "Sapan"})
create a collections
check the database
db
db.dropDatabase()
db.biodata.find({class:{$eq:12}})
db.biodata.find({class: {$in:[10,12]}})
db.biodata.find({name:{$in:["SAPAN"]}})
delete
db.biodata.drop()
return as true
show collections
> db.books.find()
> db.books.find().pretty()
6. Find Records
To find or query records, uses db.tablename.find({criteria}).
> db.books.find()
6.2 Find records where username is "google"
> db.users.find({books:"google"})
6.3 Find records where username's length is less than or equal to 2
db.users.find({$where:"this.books.length<=2"})
6.4 Find records where username field is existed.
db.users.find({6.4 Find records where username field is existed.
To drop the table, uses db.tablename.drop().
db.books.find({name:{$exists : true}})
db.books.save({"name":"Hari port"})
7. Delete Record
> db.books.remove({"name":"RESt"})
Note
To delete all records from a table, uses db.tablename.remove().
.................................................................................................................................................................................................................................
1.1. First step install mongoose
1.2. npm install --save mongoose
or
npm install --save mongoose@4.2.10 //as per choice
..........................................................................................................................................................................................................................................
Example: #1
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/app') <-- this connect method to be connection alive
Note -
explanation mongoose uses modal and schema
now what we need to do before we start entering data in our database
we need to create a schema
we need to tell the schema what kind of data we are going to be using
const carSchema = mongoose.Schema({
brand: String,
model : String.
year: Number,
avail: Boolean
})
//create a model is going to take two arguments.
// first is name of model
//second argument is going to be the schema that we're using for this database
for this document
const Car = mongoose.model('Car', carSchema );
//4 store data we will use a method for mongoose that is going to called save method
const addCar = new Car({
brand: "Ford",
model: "V2s",
year: 2018,
avail: true
})
save((err, doc)) //save take a callback
if(err) return console.log(err)
console.log(doc)
...................................Lets Try .......................
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const schema = mongoose.Schema;
//connect
mongoose.connect('mongodb://localhost:27017/Myapp')
const db = mongoose.connection;
//check connection
db.once('open', function(){
console.log('Connection succesfull')
})
//check for error Db
db.on('error', function (err){
console.log('Error', err)
})
const carSchema = new schema({
brand: String,
model: String,
year: Number,
avail: Boolean
})
const Car = mongoose.model('Car', carSchema)
const addCar = new Car({
brand: "Ford",
model: "V2s",
year: 2018,
avail: true
})
addCar.save((err, doc)=>{
if(err) return console.log(err)
console.log(doc)
})
//////////MONGOOSE /////////////////////////////MONGOOSE///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Project Structure - #1
Installations - #2
yarn add express mongoose
yarn add dotenv nodemon --dev
Code - #3
const express = require('express')
const mongoose = require('mongoose')
const app = express()
require('dotenv').config()
//Mongoose database connections
mongoose.connect(process.env.
DATABSE_URL, { useNewUrlParser: true })
const db = mongoose.connection
db.once('open', () => console.log('Database connect on successful'))
db.on('error', (error) => console.error(error))
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
.env [createa file with name .env (tips - outside of src folder)]
DATABSE_URL =mongodb://localhost/databaseName
https://github.com/sapanindia/MongooseBasic