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{ _id: 59ab1c92ea84486fb4ba9f28, username: JD, posts: [ "59ab1b43ea84486fb4ba9ef0", "59ab1b43ea84486fb4ba9ef1" ]}
1// The 2nd `populate()` call below overwrites the first because they
2// both populate 'fans'.
3Story.
4 find().
5 populate({ path: 'fans', select: 'name' }).
6 populate({ path: 'fans', select: 'email' });
7// The above is equivalent to:
8Story.find().populate({ path: 'fans', select: 'email' });
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
1//EXAMPLE ONE
2
3const mongoose = require('mongoose')
4const shortid = require('shortid')
5
6/**
7 * @description setup database connection
8 */
9
10mongoose
11 .connect('mongodb://localhost:27017/mongoose', {
12 useFindAndModify: false,
13 useUnifiedTopology: true,
14 useNewUrlParser: true
15 })
16 .then(() => console.log('Connected'))
17 .catch(() => console.log('Not Connected'))
18
19/**
20 * @description user mongoose schema
21 */
22
23const UserSchema = new mongoose.Schema(
24 {
25 fullName: {
26 type: String,
27 trim: true,
28 required: true
29 },
30 courseId: {
31 type: String,
32 ref: 'Course',
33 default: shortid.generate
34 }
35 },
36 { timestamps: true }
37)
38
39const User = mongoose.model('User', UserSchema, 'User')
40
41/**
42 * @description course mongoose schema
43 */
44
45const CourseSchema = new mongoose.Schema(
46 {
47 userId: { type: mongoose.Types.ObjectId },
48 course: []
49 },
50 { timestamps: true }
51)
52
53const Course = mongoose.model('Course', CourseSchema)
54
55/**
56 * @description register user account
57 */
58
59async function registerAccount() {
60 const user = await User.create({ fullName: 'john doe' })
61
62 await Course.create({ userId: user._id })
63
64 console.log('register successfuly')
65 process.exit(0)
66}
67//registerAccount
68
69/**
70 * @description buy video course
71 */
72
73async function buyCourse() {
74 const user = await User.findOne({ fullName: 'john doe' })
75
76 const course = await Course.updateOne(
77 { userId: user._id },
78 {
79 $push: {
80 course: {
81 $each: [
82 { name: 'react for beginner', price: 95000 },
83 { name: 'vue for beginner', price: 85000 },
84 { name: 'angular for beginner', price: 75000 }
85 ]
86 }
87 }
88 }
89 )
90
91 console.log('sucessfuly to buy course')
92 process.exit(0)
93}
94// buyCourse()
95
96/**
97 * @description results all course after buy course
98 */
99
100async function resultsCourse() {
101 const user = await User.findOne({ fullName: 'john doe' })
102
103 const courseResult = await Course.findOne({ userId: user._id })
104 .populate({
105 path: 'userId',
106 select: 'course firstName lastName'
107 })
108 .lean()
109
110 console.log({
111 fullname: user.fullName,
112 courses: courseResult.course
113 })
114 process.exit(0)
115}
116resultsCourse()
117