aldikhan13

3 METHOD POPULATE IN MONGOOSE

Aug 22nd, 2020 (edited)
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * ======================================
  3.  * EXAMPLE ONE POPULATE METHOD MONGOOSE
  4.  *=======================================
  5.  *
  6.  */
  7.  
  8. const mongoose = require('mongoose')
  9. const shortid = require('shortid')
  10.  
  11. /**
  12.  * @description setup database connection
  13.  */
  14.  
  15. mongoose
  16.   .connect('mongodb://localhost:27017/mongoose', {
  17.     useFindAndModify: false,
  18.     useUnifiedTopology: true,
  19.     useNewUrlParser: true
  20.   })
  21.   .then(() => console.log('Connected'))
  22.   .catch(() => console.log('Not Connected'))
  23.  
  24. /**
  25.  * @description user mongoose schema
  26.  */
  27.  
  28. const UserSchema = new mongoose.Schema(
  29.   {
  30.     fullName: {
  31.       type: String,
  32.       trim: true,
  33.       required: true
  34.     },
  35.     courseId: {
  36.       type: String,
  37.       ref: 'Course',
  38.       default: shortid.generate
  39.     }
  40.   },
  41.   { timestamps: true }
  42. )
  43.  
  44. const User = mongoose.model('User', UserSchema, 'User')
  45.  
  46. /**
  47.  * @description course mongoose schema
  48.  */
  49.  
  50. const CourseSchema = new mongoose.Schema(
  51.   {
  52.     userId: { type: mongoose.Types.ObjectId },
  53.     course: []
  54.   },
  55.   { timestamps: true }
  56. )
  57.  
  58. const Course = mongoose.model('Course', CourseSchema)
  59.  
  60. /**
  61.  * @description register user account
  62.  */
  63.  
  64. async function registerAccount() {
  65.   const user = await User.create({ fullName: 'john doe' })
  66.  
  67.   await Course.create({ userId: user._id })
  68.  
  69.   console.log('register successfuly')
  70.   process.exit(0)
  71. }
  72. registerAccount()
  73.  
  74. /**
  75.  * @description buy video course
  76.  */
  77.  
  78. async function buyCourse() {
  79.   const user = await User.findOne({ fullName: 'john doe' })
  80.  
  81.   const course = await Course.updateOne(
  82.     { userId: user._id },
  83.     {
  84.       $push: {
  85.         course: {
  86.           $each: [
  87.             { name: 'react for beginner', price: 95000 },
  88.             { name: 'vue for beginner', price: 85000 },
  89.             { name: 'angular for beginner', price: 75000 }
  90.           ]
  91.         }
  92.       }
  93.     }
  94.   )
  95.  
  96.   console.log('sucessfuly to buy course')
  97.   process.exit(0)
  98. }
  99. // buyCourse()
  100.  
  101. /**
  102.  * @description results all course after buy course
  103.  */
  104.  
  105. async function resultsCourse() {
  106.   const user = await User.findOne({ fullName: 'john doe' })
  107.  
  108.   const courseResult = await Course.findOne({ userId: user._id })
  109.     .populate({
  110.       path: 'userId',
  111.       select: 'course firstName lastName'
  112.     })
  113.     .lean()
  114.  
  115.   console.log({
  116.     fullname: user.fullName,
  117.     courses: courseResult.course
  118.   })
  119.   process.exit(0)
  120. }
  121. // resultsCourse()
  122.  
  123.  
  124. /**
  125.  * =====================================
  126.  * EXAMPLE TWO POPULATE METHOD MONGOOSE
  127.  *======================================
  128.  *
  129.  */
  130.  
  131. const mongoose = require('mongoose')
  132. const shortid = require('shortid')
  133.  
  134. /**
  135.  * @description setup database connection
  136.  */
  137. mongoose
  138.   .connect('mongodb://localhost:27017/mongoose', {
  139.     useFindAndModify: false,
  140.     useUnifiedTopology: true,
  141.     useNewUrlParser: true
  142.   })
  143.   .then(() => console.log('Connected'))
  144.   .catch(() => console.log('Not Connected'))
  145.  
  146. /**
  147.  * @description course mongoose schema
  148.  */
  149.  
  150. const CourseSchema = new mongoose.Schema(
  151.   {
  152.     userId: { type: mongoose.Types.ObjectId },
  153.     course: []
  154.   },
  155.   { timestamps: true }
  156. )
  157.  
  158. const Course = mongoose.model('Course', CourseSchema, 'Course')
  159.  
  160. /**
  161.  * @description user mongoose schema
  162.  */
  163.  
  164. const UserSchema = new mongoose.Schema(
  165.   {
  166.     fullName: {
  167.       type: String,
  168.       trim: true,
  169.       required: true
  170.     },
  171.     courseId: {
  172.       type: String,
  173.       ref: 'Course',
  174.       default: shortid.generate
  175.     }
  176.   },
  177.   { timestamps: true }
  178. )
  179.  
  180. UserSchema.post('save', async function (doc, next) {
  181.   if (doc) {
  182.     await Course.create({ userId: doc._id })
  183.     next()
  184.   }
  185. })
  186.  
  187. const User = mongoose.model('User', UserSchema, 'User')
  188.  
  189. /**
  190.  * @description register user account
  191.  */
  192.  
  193. async function registerAccount() {
  194.   const userData = new User({ fullName: 'john doe' })
  195.   await userData.save()
  196.  
  197.   console.log('register successfuly')
  198.   process.exit(0)
  199. }
  200. registerAccount()
  201.  
  202. /**
  203.  * @description buy video course
  204.  */
  205.  
  206. async function buyCourse() {
  207.   const user = await User.findOne({ fullName: 'john doe' })
  208.  
  209.   const course = await Course.updateOne(
  210.     { userId: user._id },
  211.     {
  212.       $push: {
  213.         course: {
  214.           $each: [
  215.             { name: 'react for beginner', price: 95000 },
  216.             { name: 'vue for beginner', price: 85000 },
  217.             { name: 'angular for beginner', price: 75000 }
  218.           ]
  219.         }
  220.       }
  221.     }
  222.   )
  223.  
  224.   console.log('sucessfuly to buy course')
  225.   process.exit(0)
  226. }
  227. // buyCourse()
  228.  
  229. /**
  230.  * @description results all course after buy course
  231.  */
  232.  
  233. async function resultsCourse() {
  234.   const user = await User.findOne({ fullName: 'john doe' })
  235.  
  236.   const courseResult = await Course.findOne({ userId: user._id })
  237.     .populate({
  238.       path: 'userId',
  239.       select: 'course firstName lastName'
  240.     })
  241.     .lean()
  242.  
  243.   console.log({
  244.     fullname: user.fullName,
  245.     courses: courseResult.course
  246.   })
  247.   process.exit(0)
  248. }
  249. // resultsCourse()
  250.  
  251.  
  252. /**
  253.  * =======================================
  254.  * EXAMPLE THREE POPULATE METHOD MONGOOSE
  255.  *========================================
  256.  *
  257.  */
  258.  
  259. const mongoose = require('mongoose')
  260. const shortid = require('shortid')
  261.  
  262. /**
  263.  * @description setup database connection
  264.  */
  265.  
  266. mongoose
  267.   .connect('mongodb://localhost:27017/mongoose', {
  268.     useFindAndModify: false,
  269.     useUnifiedTopology: true,
  270.     useNewUrlParser: true
  271.   })
  272.   .then(() => console.log('Connected'))
  273.   .catch(() => console.log('Not Connected'))
  274.  
  275. /**
  276.  * @description user mongoose schema
  277.  */
  278.  
  279. const UserSchema = new mongoose.Schema(
  280.   {
  281.     fullName: {
  282.       type: String,
  283.       trim: true,
  284.       required: true
  285.     }
  286.   },
  287.   { timestamps: true }
  288. )
  289.  
  290. UserSchema.virtual('videos', {
  291.   ref: 'Course',
  292.   localField: '_id',
  293.   foreignField: 'userId'
  294. })
  295.  
  296. UserSchema.set('toObject', { virtuals: true })
  297.  
  298. /**
  299.  * @description course mongoose schema
  300.  */
  301.  
  302. const CourseSchema = new mongoose.Schema(
  303.   {
  304.     userId: { type: mongoose.Types.ObjectId },
  305.     course: []
  306.   },
  307.   { timestamps: true }
  308. )
  309.  
  310. const User = mongoose.model('User', UserSchema, 'User')
  311. const Course = mongoose.model('Course', CourseSchema)
  312.  
  313. /**
  314.  * @description register user account
  315.  */
  316.  
  317. async function registerAccount() {
  318.   const user = await User.create({ fullName: 'john doe' })
  319.  
  320.   await Course.create({ userId: user._id })
  321.  
  322.   console.log('register successfuly')
  323.   process.exit(0)
  324. }
  325. registerAccount()
  326.  
  327. /**
  328.  * @description buy video course
  329.  */
  330.  
  331. async function buyCourse() {
  332.   const user = await User.findOne({ fullName: 'john doe' })
  333.  
  334.   const course = await Course.updateOne(
  335.     { userId: user._id },
  336.     {
  337.       $push: {
  338.         course: {
  339.           $each: [
  340.             { name: 'react for beginner', price: 95000 },
  341.             { name: 'vue for beginner', price: 85000 },
  342.             { name: 'angular for beginner', price: 75000 }
  343.           ]
  344.         }
  345.       }
  346.     }
  347.   )
  348.  
  349.   console.log('sucessfuly to buy course')
  350.   process.exit(0)
  351. }
  352. // buyCourse()
  353.  
  354. /**
  355.  * @description results all course after buy course
  356.  */
  357.  
  358. async function resultsCourse() {
  359.   const user = await User.findOne().populate('videos').lean()
  360.  
  361.   console.log({
  362.     fullname: user.fullName,
  363.     courses: user.videos.map((v) => v.course[0])
  364.   })
  365.   process.exit(0)
  366. }
  367. // resultsCourse()
  368.  
Add Comment
Please, Sign In to add comment