Mongodb Relational Documents with Node.js and Express

npm init -y
npm install express mongoose nodemon cors dotenv moment
{"name": "relational-documents","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","dev": "nodemon server.js"},"keywords": [],"author": "","license": "ISC","dependencies": {"cors": "^2.8.5","express": "^4.18.1","mongoose": "^6.6.5","nodemon": "^2.0.20"}}
require('dotenv').config()const express = require("express");const app = express();const bodyParser = require("body-parser");var cors = require("cors");
const moment = require("moment");
app.use(bodyParser.urlencoded());app.use(bodyParser.json());app.use(cors());var mongoose = require("mongoose");const mongoAtlasUri = `mongodb://localhost:27017/mongooseRelationExample`try {// Connect to the MongoDB clustermongoose.connect(mongoAtlasUri,{ useNewUrlParser: true, useUnifiedTopology: true },() => console.log("Mongoose is connected"),);} catch (e) {console.log("could not connect");}const dbConnection = mongoose.connection;dbConnection.on("error", (err) => console.log(`Connection error ${err}`));dbConnection.once("open", () => console.log("Connected to DB!"));app.use((_, res) =>{res.send({message: 'Not found!'})});app.listen(5000, (req, res)=>{console.log("Server is listening on port 5000");})
npm run dev
const mongoose = require('mongoose');const { Schema } = mongoose;const personSchema = new mongoose.Schema({first_name:{type: String},last_name:{type: String},creation_date: {type: String},updation_date: {type: String}})module.exports = mongoose.model('Person', personSchema);
app.post("/person/create", (req, res)=>{try {const person = new Person({first_name: req.body.first_name,last_name: req.body.last_name,creation_date: moment().format("MMMM Do YYYY, h:mm:ss a")});person.save();res.send({status: 'success',message: `${req.body.first_name} successfully added!`});} catch (error) {console.log(error)res.send({status: 'error',message: error});}});
var mongoose = require("mongoose");const Person = require('./models/person');
const mongoose = require('mongoose');const { Schema } = mongoose;const taskSchema = new mongoose.Schema({task_name: {type: String},task_status: {type: String,default: "pending"},assigned_to: {type: mongoose.Schema.Types.ObjectId,ref: 'Person'},creation_date: {type: String},updation_date: {type: String}})module.exports = mongoose.model('Task', taskSchema);
app.post("/task/create", (req, res)=>{try {const task = new Task({task_name: req.body.name,assigned_to: req.body.personId,creation_date: moment().format("MMMM Do YYYY, h:mm:ss a")});task.save();res.send({status: 'success',message: `${req.body.task_name} successfully added!`});} catch (error) {console.log(error)res.send({status: 'error',message: error});}});
app.get("/tasks/view", (req, res)=>{Task.find().populate('assigned_to').exec(function(error, docs){if(!error){res.status(200).json({status: "success",data: docs})}else{console.log(error)res.send({status: "error",error: error})}})})

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.