我正在尝试使用与之相关的教程来填充标签,当我在查询中使用.populate()时,它可以工作,但是当我直接在模型上进行操作时,我会有一个inifite循环。
这是我的代码:
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;
我想知道导致无限循环的原因,为什么它对查询有效但对模型无效?谢谢!
修改
这是有效的代码
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
}
});
答案 0 :(得分:0)
我最近遇到了一个相同的问题,花了相当长的时间才弄清楚,在我的情况下,两个查询相互填充并导致无限循环。