MongoDB Topics
Day 29:
- Mongoose ODM for Node.js
- Connect
- Schema
- Model
- Connection of Front-End + Back-End + Data Base
- React.js + Node.js + MongoDB
Mongoose ODM for Node.js :
Mongoose.js:
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/myDataBase",{
useNewUrlParser: true,
useUnifiedTopology: true,
})
const userSchema = new mongoose.Schema({
username: String,
email: String,
password: String
})
const User = mongoose.model('User',userSchema)
const newUser = new User({
username:"Hema",
email:"hema@gmail.com",
password: "123"
})
newUser.save().then((user)=>{
console.log(user)
}).catch((err)=>{
console.log(err)
})
User.updateOne({username:"Hema"},{password:"hema@123"}).then((result)=>{
console.log(result)
})
Connection of Front-End + Back-End + Data Base:
server.js:
const mongoose = require('mongoose');
const express = require('express');
const cors = require('cors')
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json())
app.use(cors())
app.post("/submitFormData", (req,res)=>{
const formData = req.body;
const artFormData = new ArtForm({
name:formData.name,
age:formData.age,
artworkDescription:formData.artworkDescription
})
artFormData.save().then((result)=>{
console.log(result)
res.status(200).json({ message: "Form submitted successfully!" });
})
})
mongoose.connect("mongodb://localhost:27017/myDataBase",{
useNewUrlParser: true,
useUnifiedTopology: true,
})
const ArtSchema = new mongoose.Schema({
name:String,
age:String,
artworkDescription:String
})
const ArtForm = mongoose.model("ArtForm", ArtSchema)
// const newArtForm = ArtForm({
// name:"Mahesh",
// age:"23",
// artworkDescription:"Nice work"
// })
// newArtForm.save()
const PORT = 3001
app.listen(PORT,()=>{
console.log(`Server is running on port ${PORT}`)
})
ArtCompetitionForm.js:
fetch("http://localhost:3001/submitFormData",{
method:"POST",
headers:{
"Content-Type" : "application/json"
},
body:JSON.stringify(formData)
}).then((result)=>{
console.log(result,"Form submitted successfully!")
}).catch((err)=>{
console.log(err)
})
Interview Questions:
1. How do you connect to a MongoDB database using Mongoose?
2. How do you create a Mongoose Schema?
3. What is a Mongoose Model?
4. How do you establish a connection between Node.js and MongoDB in a MERN stack application?
5. How can you handle CORS issues when connecting a React.js frontend to a Node.js backend?
No comments:
Post a Comment