I am new to mongodb and I want to have a one to few relationship in my database. I want to have an embedded schema but I am struggling to make it work. I want a user to have many posts but when I am trying to insert data then only name,email and password are getting inserted and not blogs. I am stuck and any help would be appreciated.
import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import Cors from "cors";
const app=express();
const port= process.env.PORT || 5000;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());
app.use(Cors());
mongoose.connect('mongodb+srv://@cluster0.gmg3q.mongodb.net/NotScr?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true});
const userSchema=mongoose.Schema({
name: String,
email: String,
password: String,
blog: [{
title: String,
post: String
}]
});
const User= mongoose.model("User", userSchema);
app.get("/", (req,res)=>{
res.send("Hello World!Welcome to NOTSCRAP backend");
});
app.post("/register", (req,res)=>{
const newUser = req.body;
User.create(newUser, (err, data) => {
if(err){
res.send(err)
} else{
res.send(data);
}
});
});
app.post("/login", (req, res)=>{
const user_email = req.body.email;
const user_password = req.body.password;
User.findOne({email: user_email}, function(err, foundUser){
if(err){
console.log("Wrong Email");
res.send("Wrong Email");
} else{
if(foundUser){
if(foundUser.password === user_password){
console.log(foundUser);
res.send(foundUser);
} else{
console.log("Wrong Password");
res.send("Wrong Password");
}
} else{
res.send("Wrong Email");
console.log("Wrong Email");
}
}
});
console.log(req.body);
});
app.post("/userdata", (req, res) =>{
console.log(req.body);
const id=req.body.username;
User.findOne({_id: id}, function(err, foundUser){
if(err){
console.log(err)
} else{
console.log(foundUser);
res.send(foundUser);
}
});
});
app.listen(port, ()=>{
console.log(`Server is up and running on port ${port}`);
})