I have a file model referencing a note model with the note referencing a question model.
A file can have many notes and different notes can have many questions, how can I query a file by its ID in MongoDB to return all the questions under all notes which are under a file.
File--->Notes--->Questions
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
const fileSchema = new Schema(
{
title: {
type: String,
required: [true, 'Please add a title'],
trim: true,
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
notes: [
{
type: mongoose.Schema.ObjectId,
ref: 'Note',
},
],
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
module.exports = mongoose.model('File', fileSchema);
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
const noteSchema = new Schema(
{
title: {
type: String,
required: [true, 'Please add a title'],
trim: true,
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
questions: [
{
type: mongoose.Schema.ObjectId,
ref: 'Question',
},
],
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
This looks similar to Mongoose's example of Populating across multiple levels
Say you have a user schema which keeps track of the user's friends.
const userSchema = new Schema({ name: String, friends: [{ type: ObjectId, ref: 'User' }] });Populate lets you get a list of a user's friends, but what if you also wanted a user's friends of friends? Specify the populate option to tell mongoose to populate the friends array of all the user's friends:
User. findOne({ name: 'Val' }). populate({ path: 'friends', // Get friends of friends - populate the 'friends' array for every friend populate: { path: 'friends' } });
In your case it may look like this:
File
.findById(id)
.populate({
path: 'notes',
populate: { path: 'questions' }
});