-
Notifications
You must be signed in to change notification settings - Fork 0
/
population.js
54 lines (43 loc) · 1.14 KB
/
population.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
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser:true})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
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'
}
}));
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);
}
// createAuthor('Mosh', 'My bio', 'My Website');
// createCourse('Node Course', '5bdaa0ababd8134db8652913')
listCourses();