【发布时间】:2022-01-21 17:27:34
【问题描述】:
我想知道您是否可以使用 MongoDB 进行动态深度填充,特别是我在快速应用程序上使用 mongoose。我正在尝试构建一个基本的 reddit 克隆。在我的 Post 模型上,我正在尝试创建一个回复链。回复可能会嵌套,因为有人可以回复回复的回复。我可以填充该回复链吗?我只能弄清楚如何填充第一层回复。基于阅读文档并查看有关堆栈溢出的其他回答者,我认为这是不可能的,但我想在我重塑我的数据之前提出这个问题。这是我的帖子模型:
const postSchema = new mongoose.Schema(
{
content: {
type: String,
required: [true, 'A post can not be empty'],
},
thread: {
type: mongoose.Schema.ObjectId,
ref: 'Thread',
},
isReply: {
type: Boolean,
default: false,
},
parentPost: {
type: mongoose.Schema.ObjectId,
ref: 'Post',
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
postSchema.virtual('replies', {
ref: 'Post',
foreignField: 'parentPost',
localField: '_id',
});
以及我正在执行查询并尝试填充回复链的线程处理程序:
exports.getThread = factory.getOne(Thread, 'thread', {
path: 'posts',
// Deep populate the replies from each post
populate: { path: 'replies' },
});
// This is the factory getOne function
exports.getOne = (Model, modelName, popOptions) =>
catchAsync(async (req, res, next) => {
const query = popOptions
? Model.findById(req.params.id).populate(popOptions)
: Model.findById(req.params.id);
const doc = await query;
if (!doc)
return next(
new AppError(`No ${modelName} could be found with that id`, 404)
);
res.status(200).json({
status: 'success',
data: { [modelName]: doc },
});
});
【问题讨论】:
-
这能回答你的问题吗? mongoose recursive populate
标签: javascript mongodb express mongoose