1Story.
2 findOne({ title: /casino royale/i }).
3 populate('author', 'name'). // only return the Persons name
4 exec(function (err, story) {
5 if (err) return handleError(err);
6
7 console.log('The author is %s', story.author.name);
8 // prints "The author is Ian Fleming"
9
10 console.log('The authors age is %s', story.author.age);
11 // prints "The authors age is null'
12 });
1const storySchema = Schema({
2 authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
3 title: String
4});
5
6// Later
7
8const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
9story.authors; // `[]`
1// populates a single object
2User.findById(id, function (err, user) {
3 const opts = [
4 { path: 'company', match: { x: 1 }, select: 'name' },
5 { path: 'notes', options: { limit: 10 }, model: 'override' }
6 ];
7
8 User.populate(user, opts, function (err, user) {
9 console.log(user);
10 });
11});
12
13// populates an array of objects
14User.find(match, function (err, users) {
15 const opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];
16
17 const promise = User.populate(users, opts);
18 promise.then(console.log).end();
19})
20
21// imagine a Weapon model exists with two saved documents:
22// { _id: 389, name: 'whip' }
23// { _id: 8921, name: 'boomerang' }
24// and this schema:
25// new Schema({
26// name: String,
27// weapon: { type: ObjectId, ref: 'Weapon' }
28// });
29
30const user = { name: 'Indiana Jones', weapon: 389 };
31Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
32 console.log(user.weapon.name); // whip
33})
34
35// populate many plain objects
36const users = [{ name: 'Indiana Jones', weapon: 389 }]
37users.push({ name: 'Batman', weapon: 8921 })
38Weapon.populate(users, { path: 'weapon' }, function (err, users) {
39 users.forEach(function (user) {
40 console.log('%s uses a %s', users.name, user.weapon.name)
41 // Indiana Jones uses a whip
42 // Batman uses a boomerang
43 });
44});
45// Note that we didn't need to specify the Weapon model because
46// it is in the schema's ref
1//EXAMPLE TWO
2
3const mongoose = require('mongoose')
4const shortid = require('shortid')
5
6/**
7 * @description setup database connection
8 */
9mongoose
10 .connect('mongodb://localhost:27017/mongoose', {
11 useFindAndModify: false,
12 useUnifiedTopology: true,
13 useNewUrlParser: true
14 })
15 .then(() => console.log('Connected'))
16 .catch(() => console.log('Not Connected'))
17
18/**
19 * @description course mongoose schema
20 */
21
22const CourseSchema = new mongoose.Schema(
23 {
24 userId: { type: mongoose.Types.ObjectId },
25 course: []
26 },
27 { timestamps: true }
28)
29
30const Course = mongoose.model('Course', CourseSchema, 'Course')
31
32/**
33 * @description user mongoose schema
34 */
35
36const UserSchema = new mongoose.Schema(
37 {
38 fullName: {
39 type: String,
40 trim: true,
41 required: true
42 },
43 courseId: {
44 type: String,
45 ref: 'Course',
46 default: shortid.generate
47 }
48 },
49 { timestamps: true }
50)
51
52UserSchema.post('save', async function (doc, next) {
53 if (doc) {
54 await Course.create({ userId: doc._id })
55 next()
56 }
57})
58
59const User = mongoose.model('User', UserSchema, 'User')
60
61/**
62 * @description register user account
63 */
64
65async function registerAccount() {
66 const userData = new User({ fullName: 'john doe' })
67 await userData.save()
68
69 console.log('register successfuly')
70 process.exit(0)
71}
72registerAccount()
73
74/**
75 * @description buy video course
76 */
77
78async 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
105async 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