mongoose query foreign key

Solutions on MaxInterview for mongoose query foreign key by the best coders in the world

showing results for - "mongoose query foreign key"
Hajar
13 Nov 2018
1const mongoose = require('mongoose');
2
3const personSchema = mongoose.Schema({
4  _id: Schema.Types.ObjectId,
5  name: String,
6  age: Number,
7  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
8});
9
10const storySchema = mongoose.Schema({
11  author: { type: Schema.Types.ObjectId, ref: 'Person' },
12  title: String,
13  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
14});
15
16const Story = mongoose.model('Story', storySchema);
17const Person = mongoose.model('Person', personSchema);
18
19Story.
20  findOne({ title: 'Casino Royale' }).
21  populate('author').
22  exec(function (err, story) {
23    if (err) return handleError(err);
24    console.log('The author is %s', story.author.name);
25    // prints "The author is Ian Fleming"
26  });
27
Emilio
22 Jul 2018
1const mongoose = require('mongoose');
2
3const personSchema = mongoose.Schema({
4  _id: Schema.Types.ObjectId,
5  name: String,
6  age: Number,
7  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
8});
9
10const storySchema = mongoose.Schema({
11  author: { type: Schema.Types.ObjectId, ref: 'Person' },
12  title: String,
13  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
14});
15
16const Story = mongoose.model('Story', storySchema);
17const Person = mongoose.model('Person', personSchema);
18
19Story.
20  findOne({ title: 'Casino Royale' }).
21  populate('author').
22  exec(function (err, story) {
23    if (err) return handleError(err);
24    console.log('The author is %s', story.author.name);
25    // prints "The author is Ian Fleming"
26  });