-
Notifications
You must be signed in to change notification settings - Fork 0
/
practice.js
96 lines (87 loc) · 1.98 KB
/
practice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//practice
//98tdfI0W5hItcb5J
const mongoose = require('mongoose');
const uri =
'mongodb+srv://practice:98tdfI0W5hItcb5J@cluster0.2fl1l.mongodb.net/practice?retryWrites=true&w=majority';
mongoose
.connect(uri)
.then(() => {
console.log('success full connection');
})
.catch((err) => {
console.error('error is :', err);
});
// reference method
// const Author = mongoose.model(
// 'Author',
// new mongoose.Schema({
// name: String,
// bio: String,
// website: String,
// })
// );
// const Course = mongoose.model(
// 'Course',
// new mongoose.Schema({
// name: String,
// author: {
// type: mongoose.Schema.Types.ObjectId,
// ref: 'Author',
// },
// })
// );
//embeding method
const authorSchema = new mongoose.Schema({
name: String,
bio: String,
website: String,
});
const Course = mongoose.model(
'Course',
new mongoose.Schema({
name: String,
author: { type: authorSchema, required: true },
})
);
const Author = mongoose.model('Author', authorSchema);
async function createAuthor(name, bio, website) {
const author = new Author({
name,
bio,
website,
});
const result = await author.save();
console.log(result);
}
async function createCourse(name, author) {
const course = new Course({
name,
author,
});
const result = await course.save();
console.log(result);
}
async function listCourses() {
const courses = await Course.find()
.populate('author', 'name -_id')
.select('name author');
console.log(courses);
}
async function updateAuthor(courseId) {
const course = await Course.update(
{ _id: courseId },
{
$set: {
'author.name': 'embeding updated author',
},
}
);
}
//createAuthor('josh', 'My bio josh', 'My Website josh');
//createCourse('Node Course', '6219f7cfc8d2232dfb53faf5');
//listCourses();
// createCourse(
// 'Noode embeding Course',
// new Author({ name: 'embeding author' })
// );
updateAuthor('621a08945cd35441109e6858');