Skip to content

Instantly share code, notes, and snippets.

@goish135
Created December 6, 2021 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goish135/5721bfadb0e6946abcd6eef2b86113e0 to your computer and use it in GitHub Desktop.
Save goish135/5721bfadb0e6946abcd6eef2b86113e0 to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose')
const {model,Schema} = require('mongoose')
mongoose.connect('mongodb://localhost:27017/myapp',{useNewUrlParser:true});
const app = require('express')()
const DepartmentSchema = new Schema({
name: String,
location: String
}
)
var Department = model("department",DepartmentSchema)
var EmployeeSchema = new Schema({
firstName: String,
lastName: String,
mobile: String,
department: {type: Schema.Types.ObjectId,ref:'department'}
})
var Employee = model("employee",EmployeeSchema)
var CompanySchema = new Schema({
name: String,
address: String,
employee: [{type: Schema.Types.ObjectId,ref:'employee'}]
})
var Company = model("company",CompanySchema)
app.use("/",async(req,res)=> {
await Department.remove({})
await Department.create({
name: 'IT Department',
location: 'Building A'
})
await Department.create({
name: 'Marketing Department',
location: 'Building B'
})
await Employee.remove({})
await Employee.create({
firstName: 'PYSUS',
lastName: 'PY',
monile: "321",
department: await Department.findOne({name:'IT Department'})
})
await Employee.create({
firstName: 'Sunder',
lastName: 'PY',
monile: "123",
department: await Department.findOne({name:'Marketing Department'})
})
await Company.remove({})
await Company.create({
"name": 'BigCompany',
"address": 'Address',
"employee": await Employee.find()
})
res.json({
departments: await Department.find(),
employees: await Employee.find(),
employeesWithDep: await Employee.find().populate("department","name"),
company: await Company.find(),
companyWithEmp: await Company.find().populate("employee"),
companyWithEmpAndDep: await Company.find()
.populate({
path: "employee",
model: "employee",
populate: {path: "department",model:"department"}
})
}
)
})
app.listen(3050,()=> console.log("Listening on port 3050"))
{
"name": "mongoose-relation",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^6.0.14"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment