mongodb mongoose虚拟填充无限循环

xv8emn3q  于 2023-10-16  发布在  Go
关注(0)|答案(3)|浏览(133)

我试图用相关的教程填充一个标签,当我在查询上使用.populate()时,它可以工作,但是当我直接在模型上做时,我有一个无限循环。
下面是我的代码:

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;

下载.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;

下载.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
  }
});
ctrmrzij

ctrmrzij1#

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

j1dl9f46

j1dl9f462#

这发生在我身上,因为我只是虚拟中间件中的console.log({this : this})console.log(this)

h5qlskok

h5qlskok3#

我也有同样的问题。我认为使用/^find/会导致无限循环。使用“findOne”而不是/^find/拯救了我:

tagSchema.pre(findOne, function(next) {

//这是导致无限循环的代码this.populate({ path:“教程”,选择:});
return();

相关问题