mongoose pupulate code example
Example: mongoose populate
const mongoose = require('mongoose')
const shortid = require('shortid')
mongoose
.connect('mongodb://localhost:27017/mongoose', {
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log('Connected'))
.catch(() => console.log('Not Connected'))
const UserSchema = new mongoose.Schema(
{
fullName: {
type: String,
trim: true,
required: true
},
courseId: {
type: String,
ref: 'Course',
default: shortid.generate
}
},
{ timestamps: true }
)
const User = mongoose.model('User', UserSchema, 'User')
const CourseSchema = new mongoose.Schema(
{
userId: { type: mongoose.Types.ObjectId },
course: []
},
{ timestamps: true }
)
const Course = mongoose.model('Course', CourseSchema)
async function registerAccount() {
const user = await User.create({ fullName: 'john doe' })
await Course.create({ userId: user._id })
console.log('register successfuly')
process.exit(0)
}
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)
}
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()