gpt4 book ai didi

javascript - Mongoose 虚拟填充无限循环

转载 作者:行者123 更新时间:2023-12-04 13:38:58 25 4
gpt4 key购买 nike

我正在尝试使用与之相关的教程填充标签,当我在查询上使用 .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
}
});

最佳答案

我最近遇到了同样的问题,花了很长时间才弄清楚,在我的情况下,两个查询相互填充并导致无限循环。

关于javascript - Mongoose 虚拟填充无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com