populate method mongoose code example

Example 1: mongoose populate

Story.
  findOne({ title: /casino royale/i }).
  populate('author', 'name'). // only return the Persons name
  exec(function (err, story) {
    if (err) return handleError(err);

    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"

    console.log('The authors age is %s', story.author.age);
    // prints "The authors age is null'
  });

Example 2: mongoos populate a ref

const storySchema = Schema({
  authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
  title: String
});

// Later

const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors; // `[]`

Example 3: how to use mongoose populate

{   _id: 59ab1c92ea84486fb4ba9f28,  username: 'JD',  posts:    [       {         _id: 59ab1b43ea84486fb4ba9ef0,        content: "Is it dark out?"      },{        _id: 59ab1b43ea84486fb4ba9ef1,        content: "Hey anyone got a cup of sugar?"      }    ]  }

Example 4: how to use mongoose populate

function getUserWithPosts(username){  return User.findOne({ username: username })    .populate('posts').exec((err, posts) => {      console.log("Populated User " + posts);    })}

Example 5: mongoose populate

//EXAMPLE TWO

const mongoose = require('mongoose')
const shortid = require('shortid')

/**
 * @description setup database connection
 */
mongoose
  .connect('mongodb://localhost:27017/mongoose', {
    useFindAndModify: false,
    useUnifiedTopology: true,
    useNewUrlParser: true
  })
  .then(() => console.log('Connected'))
  .catch(() => console.log('Not Connected'))

/**
 * @description course mongoose schema
 */

const CourseSchema = new mongoose.Schema(
  {
    userId: { type: mongoose.Types.ObjectId },
    course: []
  },
  { timestamps: true }
)

const Course = mongoose.model('Course', CourseSchema, 'Course')

/**
 * @description user mongoose schema
 */

const UserSchema = new mongoose.Schema(
  {
    fullName: {
      type: String,
      trim: true,
      required: true
    },
    courseId: {
      type: String,
      ref: 'Course',
      default: shortid.generate
    }
  },
  { timestamps: true }
)

UserSchema.post('save', async function (doc, next) {
  if (doc) {
    await Course.create({ userId: doc._id })
    next()
  }
})

const User = mongoose.model('User', UserSchema, 'User')

/**
 * @description register user account
 */

async function registerAccount() {
  const userData = new User({ fullName: 'john doe' })
  await userData.save()

  console.log('register successfuly')
  process.exit(0)
}
registerAccount()

/**
 * @description buy video course
 */

async function buyCourse() {
  const user = await User.findOne({ fullName: 'john doe' })

  const course = await Course.updateOne(
    { userId: user._id },
    {
      $push: {
        course: {
          $each: [
            { name: 'react for beginner', price: 95000 },
            { name: 'vue for beginner', price: 85000 },
            { name: 'angular for beginner', price: 75000 }
          ]
        }
      }
    }
  )

  console.log('sucessfuly to buy course')
  process.exit(0)
}
// buyCourse()

/**
 * @description results all course after buy course
 */

async function resultsCourse() {
  const user = await User.findOne({ fullName: 'john doe' })

  const courseResult = await Course.findOne({ userId: user._id })
    .populate({
      path: 'userId',
      select: 'course firstName lastName'
    })
    .lean()

  console.log({
    fullname: user.fullName,
    courses: courseResult.course
  })
  process.exit(0)
}
// resultsCourse()

Tags:

Misc Example