Example 1: mongoose populate
Story.
findOne({ title: /casino royale/i }).
populate('author', 'name').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
console.log('The authors age is %s', story.author.age);
});
Example 2: mongodb populate document
Story.
findOne({ title: 'Casino Royale' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
});
Example 3: mongoos populate a ref
const storySchema = Schema({
authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
title: String
});
const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors;
Example 4: mongoose populate()
User.findById(id, function (err, user) {
const opts = [
{ path: 'company', match: { x: 1 }, select: 'name' },
{ path: 'notes', options: { limit: 10 }, model: 'override' }
];
User.populate(user, opts, function (err, user) {
console.log(user);
});
});
User.find(match, function (err, users) {
const opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];
const promise = User.populate(users, opts);
promise.then(console.log).end();
})
const user = { name: 'Indiana Jones', weapon: 389 };
Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
console.log(user.weapon.name);
})
const users = [{ name: 'Indiana Jones', weapon: 389 }]
users.push({ name: 'Batman', weapon: 8921 })
Weapon.populate(users, { path: 'weapon' }, function (err, users) {
users.forEach(function (user) {
console.log('%s uses a %s', users.name, user.weapon.name)
});
});
Example 5: 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 CourseSchema = new mongoose.Schema(
{
userId: { type: mongoose.Types.ObjectId },
course: []
},
{ timestamps: true }
)
const Course = mongoose.model('Course', CourseSchema, 'Course')
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')
async function registerAccount() {
const userData = new User({ fullName: 'john doe' })
await userData.save()
console.log('register successfuly')
process.exit(0)
}
registerAccount()
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)
}
Example 6: 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()