sab*_*ina 5 javascript mongoose mongodb node.js mongoose-populate
我试图用与其相关的教程填充标签,当我在查询上使用 .populate() 时,它可以工作,但是当我直接在模型上执行此操作时,我有一个无限循环。
这是我的代码:
标签.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;
Run Code Online (Sandbox Code Playgroud)
教程.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;
Run Code Online (Sandbox Code Playgroud)
我想知道是什么导致了无限循环以及为什么它适用于查询但不适用于模型?谢谢 !
编辑
这是有效的代码
标签.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;
Run Code Online (Sandbox Code Playgroud)
教程.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;
Run Code Online (Sandbox Code Playgroud)
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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1044 次 |
| 最近记录: |