如何用Mongoose查询parent数组含指定ID的MongoDB文档
Got it, let's break down how to fetch all descendants of the document with _id: 2 (your "child" entry) using Mongoose.
Looking at your data structure, each document's parent array stores the full lineage of its ancestors. So any descendant of the "child" will have 2 somewhere in its parent array. That makes the query straightforward:
Mongoose Query Code
Assuming your model is named something like Node (adjust to match your actual model name):
const Node = require('./models/node'); // Import your Mongoose model async function fetchChildDescendants() { // Find all documents where the parent array contains 2 const descendants = await Node.find({ parent: 2 }); console.log('All descendants of "child" (_id:2):', descendants); // This will return _id:3 (grandchild), _id:4, _id:5 (greatgrandchildren) } // Call the function fetchChildDescendants();
Why This Works
In MongoDB, when you query an array field with a single value (like parent: 2), it automatically matches all documents where that value exists anywhere in the array. Perfect for your use case, since all descendants of the "child" will include 2 in their ancestor lineage.
Bonus: If You Need Only Direct Children
If you ever want to fetch only direct children of "child" (just _id:3 in your sample data), you can narrow the query to match documents where 2 is the last entry in the parent array (since your lineage is ordered from root to immediate parent). Here's how:
const directChildren = await Node.find({ parent: { $size: 2, // The parent array has exactly 2 elements (root + immediate parent) $elemMatch: { $eq: 2 } // And 2 is one of those elements } });
Or using array index syntax (since the immediate parent is the last element, index 1 for an array of length 2):
const directChildren = await Node.find({ 'parent.1': 2 });
内容的提问来源于stack exchange,提问作者Leo Alfando

