I'm trying to populate a tag with the tutorials that are related to it, when I use .populate() on the query it works, but when I do it directly on the model I have an inifite loop.
Here's my code:
Tag.js
const mongoose = require("mongoose");
const tagSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
trim: true
}
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
}
);
tagSchema.virtual("tutorials", {
ref: "Tutorial",
foreignField: "tags",
localField: "_id"
});
tagSchema.pre(/^find/, function(next) {
// That's the code that causes an infinite loop
this.populate({
path: "tutorials",
select: "-__v"
});
next();
});
const Tag = mongoose.model("Tag", tagSchema);
module.exports = Tag;
Tutorial.js
const mongoose = require('mongoose');
const tutorialSchema = new mongoose.Schema({
title: {
type: String,
required: true,
unique: true,
trim: true
},
tags: {
type: [
{
type: mongoose.Schema.ObjectId,
ref: 'Tag'
}
]
}
});
const Tutorial = mongoose.model('Tutorial', tutorialSchema);
module.exports = Tutorial;
I'd like to know what causes the infinite loop and why does it work on the query but not on the model ? Thanks !
Edit
Here's the code that works
Tag.js
const mongoose = require("mongoose");
const tagSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
trim: true
}
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
}
);
tagSchema.virtual("tutorials", {
ref: "Tutorial",
foreignField: "tags",
localField: "_id"
});
const Tag = mongoose.model("Tag", tagSchema);
module.exports = Tag;
Tutorial.js
const mongoose = require('mongoose');
const tutorialSchema = new mongoose.Schema({
title: {
type: String,
required: true,
unique: true,
trim: true
},
tags: {
type: [
{
type: mongoose.Schema.ObjectId,
ref: 'Tag'
}
]
}
});
const Tutorial = mongoose.model('Tutorial', tutorialSchema);
module.exports = Tutorial;
TagController.js
const Tag = require('./../models/tagModel');
exports.getAllTags = async (req, res) => {
try {
const docs = await Tag.find().populate({
path: 'tutorials',
select: '-__v'
});
res.status(200).json({
// some code
});
} catch(err) => {
// some code
}
});