-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMongoDB_Data_Population_Reference.txt
58 lines (48 loc) · 1.43 KB
/
MongoDB_Data_Population_Reference.txt
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
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
gender: String,
contact: Number,
email: String,
stories: [{ type: String, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Person = mongoose.model('Person', personSchema);
const Story = mongoose.model('Story', storySchema);
module.exports = {Person, Story}
const author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Darpan Chachpara',
age: 24,
gender: "Male",
contact: 75868,
email: "darpan@gmail.com",
stories: "Robbery"
});
author.save(function (err) {
if (err) return handleError(err);
const story1 = new Story({
title: 'Money Heist',
author: author._id, // assign the _id from the person
fans: "Dc_126_111"
});
story1.save(function (err) {
if (err) return handleError(err);
// that's it!
});
});
Story.
findOne({ title: 'Money Heist' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
// prints "The author is Darpan Chachpara"
});