const categorySlug = req.query.category; const category = await Category.findOne({ slug: categorySlug }); const children = await Category.find({ parent: category._id }); Is it possible to combine those two queries into one? I tried doing something like
const children = await Category.aggregate([ { $match: { slug: categorySlug, }, }, { // somehow use the _id field from document fetched in first stage } ]); But I have no idea if this is even possible.
EDIT:
const document = await Category.aggregate([ { $match: { slug: categorySlug, }, }, { $lookup: { from: 'categories', localField: '_id', foreignField: 'parent', as: 'children', }, }, ]); const desiredResult = document[0].children; This works but is there a way to do this fully in the aggregation pipeline? Basically I want to get ONLY the "children" array, nothing else.
https://stackoverflow.com/questions/66727802/findone-then-findmany-using-value-from-document-found-in-findone-in-a-single-qu March 21, 2021 at 08:34AM
没有评论:
发表评论