1

I have below collection:

[{
    "_id":  "60035d0a1599912a5c814e58",
    "idUsuario": "600365521599912a5c814e5e",
    "parentNode": "",
    "piernaPadre": "",
    "estado": "1"
    },
    {
    "_id": "6003827b06b4423c9ca7e6aa",
    "idUsuario": "60036e53dda7df34749ebf3a",
    "parentNode": "60035d0a1599912a5c814e58",
    "piernaPadre": "d",
    "estado": 1
    },
    {
    "_id": "60038c92ea7d593fe029cc0f",
    "idUsuario": "600382a506b4423c9ca7e6ab",
    "parentNode": "6003827b06b4423c9ca7e6aa",
    "piernaPadre": "d",
    "estado": 1
}]

I need to get the descendants of a node, I'm trying with $graphLookup,

$graphLookup: {
          from: "nodoModel",
          startWith: "$_id",
          connectFromField: "_id",
          connectToField: "parentNode",
          as: "arrayDes"
        }

but does not work, the return is void. Is there a mistake?

Thanks.

EDIT 1

Now I can get a result when try to get de ancestors of a node:

 $graphLookup: {
          from: "nodos",
          startWith: "$_id",
          connectFromField: "_id",
          connectToField: "nodoPadre",
          as: "padre"
        }

Whit below result:

[
    {
    _id: 60035d0a1599912a5c814e58,
    idUsuario: '600365521599912a5c814e5e',
    parentNode: '',
    piernaPadre: '',
    estado: '1',
    padre: [ [Object] ]
    },
    {
    _id: 6004589436a40941f48121f8,
    idUsuario: '600365e9ccf1e51b2cab341f',
    parentNode: '60035d0a1599912a5c814e58',
    piernaPadre: 'd',
    estado: 1,
    createdAt: 2021-01-17T15:32:36.986Z,
    updatedAt: 2021-01-17T15:32:36.986Z,
    __v: 0,
    padre: [ [Object] ]
    },
    {
    _id: 6004592936a40941f48121fa,
    idUsuario: '6004591536a40941f48121f9',
    parentNode: '6004589436a40941f48121f8',
    piernaPadre: 'd',
    estado: 1,
    createdAt: 2021-01-17T15:35:05.626Z,
    updatedAt: 2021-01-17T15:35:05.626Z,
    __v: 0,
    padre: [ [Object] ]
    }
]

But I need to get the descendants not the ancestors

EDIT 2

(in the original model parentNode is named nodoPadre)

It is a screenshot of my code: enter image description here

and that is the console.log: enter image description here

arrayDes is a void array. I'm using mongoose, maybe it is related with the problem?

EDIT 3

I'm trying to change type of nodoPadre to objectId enter image description here

AndresChica
  • 155
  • 1
  • 13
  • 1
    i can not see `pierna` field in your document that you are match condition in `restrictSearchWithMatch`, can you post your expected result. – turivishal Jan 17 '21 at 07:05
  • I updated the question, please ommit the restrictSearchWithMatch, it does not matter yet. Thanks for comment – AndresChica Jan 17 '21 at 16:17
  • 1
    are you looking for this? [playground](https://mongoplayground.net/p/9cI7L2f65BL) – turivishal Jan 17 '21 at 16:27
  • Yes it is!!!, but for some reason I got void array, I edit the question with the code. by the way I'm using mongoose – AndresChica Jan 17 '21 at 17:21
  • 1
    can you confirm what is the type of `parentNode`, or `nodoPadre` in collection? is it string type or object type? – turivishal Jan 17 '21 at 17:23
  • nodoPadre is string. This is its definition nodoPadre: { type: String, required: [true, '2'], index: true, } – AndresChica Jan 17 '21 at 17:27
  • 1
    that is the issue, _id have object id type and nodoPadre is string, both should be same. – turivishal Jan 17 '21 at 17:30
  • Understood. Now I'm trying to change type of nodoPadre but does not recognized – AndresChica Jan 17 '21 at 17:39
  • 1
    okay update `nodoPadre` type to object id in all documents, and change type in schema to `type: mongoose.Types.ObjectId` – turivishal Jan 17 '21 at 17:39
  • Thank you very much for your help, finally I could get the desired result. Do you want to post your answer so I can choose as best answer?. Thanks for your patience – AndresChica Jan 17 '21 at 18:22

2 Answers2

1

Try query to get descendants,

  • $match put condition
  • $grouphLookup same as yours
  { $match: { nodoPadre: "" } },
  {
    $graphLookup: {
      from: "collection",
      startWith: "$_id",
      connectFromField: "_id",
      connectToField: "nodoPadre",
      as: "arrayDes"
    }
  }

Playground


For your Second Edit:

Update nodoPadre type to object id type in all documents, and change type in schema to type: mongoose.Types.ObjectId

nodoPadre: {
  type: mongoose.Types.ObjectId,
  required: [false, '2'],
  index: true
}
turivishal
  • 34,368
  • 7
  • 36
  • 59
1

I had the same issue and finally I resolved it by chnaging the collection name to small letters and it should be plural based on mongodb . Here is my details

Mongoose schema:

const fileFolderSchema = new Schema({
    name: String,
    parentFolder: {type: Mongoose.Types.ObjectId, ref: "FileFolder"},
    path: String,
    metadata: {
        type: metaDataSchema
    }
}, { id: false }).set('toJSON', {
    virtuals: true
});

export const FileFolder = Mongoose.model('FileFolder', fileFolderSchema);

Nodejs Method:

    folder_tree_structure: async(ctx:any) => {
        try {
          let treeStructure =  await FileFolder.aggregate([
            {
                $match: {
                  parentFolder: {
                    $exists: true
                  }
                }
              },
              {
                $graphLookup: {
                  from: 'filefolders', // here your collection name is always small letters and plural
                  startWith: '$_id',
                  connectFromField: 'parentFolder',
                  connectToField: 'parentFolder',
                  maxDepth: 1,
                  depthField: 'depth',
                  as: 'TreeResult'
                }
              }
              ]);
            console.log('tree structure',treeStructure )
            ctx.status = 200;
            ctx.body = treeStructure;
        } catch (err) {
            ctx.status = 400;
            ctx.body = 'Not found' 
        }
    } 

My Nodejs response:

[
    {
        "_id": "636cd1d2692344da47f3e2f0",
        "name": "Folder2",
        "path": "files/Folder2",
        "metadata": {
            "version": 1,
            "created_by": "user-1",
            "created_on": "2022-11-10T10:26:26.828Z",
            "timeout": -1
        },
        "__v": 0,
        "parentFolder": "636cd213692344da47f3e2f5",
        "TreeResult": [
            {
                "_id": "636cd238692344da47f3e301",
                "name": "Folder3",
                "path": "files/Folder3",
                "metadata": {
                    "version": 1,
                    "created_by": "user-1",
                    "created_on": "2022-11-10T10:28:08.655Z",
                    "timeout": -1
                },
                "__v": 0,
                "parentFolder": "636cd1d2692344da47f3e2f0",
                "depth": 0
            },
            {
                "_id": "636d075874867ade3d3c3224",
                "name": "images",
                "path": "files/images",
                "metadata": {
                    "version": 1,
                    "created_by": "user-1",
                    "created_on": "2022-11-10T14:14:48.871Z",
                    "timeout": -1
                },
                "__v": 0,
                "parentFolder": "636cd1d2692344da47f3e2f0",
                "depth": 0
            }
        ]
    },
    {
        "_id": "636cd213692344da47f3e2f5",
        "name": "Folder1",
        "path": "files/Folder1",
        "metadata": {
            "version": 1,
            "created_by": "user-1",
            "created_on": "2022-11-10T10:27:31.600Z",
            "timeout": -1
        },
        "__v": 0,
        "parentFolder": "636cd213692344da47f3e2f5",
        "TreeResult": [
            {
                "_id": "636cd213692344da47f3e2f5",
                "name": "Folder1",
                "path": "files/Folder1",
                "metadata": {
                    "version": 1,
                    "created_by": "user-1",
                    "created_on": "2022-11-10T10:27:31.600Z",
                    "timeout": -1
                },
                "__v": 0,
                "parentFolder": "636cd213692344da47f3e2f5",
                "depth": 0
            },
            {
                "_id": "636cd1d2692344da47f3e2f0",
                "name": "Folder2",
                "path": "files/Folder2",
                "metadata": {
                    "version": 1,
                    "created_by": "user-1",
                    "created_on": "2022-11-10T10:26:26.828Z",
                    "timeout": -1
                },
                "__v": 0,
                "parentFolder": "636cd213692344da47f3e2f5",
                "depth": 0
            },
            {
                "_id": "636ce2452e97522606b14b23",
                "name": "images",
                "path": "files/images",
                "metadata": {
                    "version": 1,
                    "created_by": "user-1",
                    "created_on": "2022-11-10T11:36:37.691Z",
                    "timeout": -1
                },
                "__v": 0,
                "parentFolder": "636cd213692344da47f3e2f5",
                "depth": 0
            }
        ]
    },
    {
        "_id": "636cd238692344da47f3e301",
        "name": "Folder3",
        "path": "files/Folder3",
        "metadata": {
            "version": 1,
            "created_by": "user-1",
            "created_on": "2022-11-10T10:28:08.655Z",
            "timeout": -1
        },
        "__v": 0,
        "parentFolder": "636cd1d2692344da47f3e2f0",
        "TreeResult": []
    },
    {
        "_id": "636ce2452e97522606b14b23",
        "name": "images",
        "path": "files/images",
        "metadata": {
            "version": 1,
            "created_by": "user-1",
            "created_on": "2022-11-10T11:36:37.691Z",
            "timeout": -1
        },
        "__v": 0,
        "parentFolder": "636cd213692344da47f3e2f5",
        "TreeResult": []
    },
    {
        "_id": "636d075874867ade3d3c3224",
        "name": "images",
        "path": "files/images",
        "metadata": {
            "version": 1,
            "created_by": "user-1",
            "created_on": "2022-11-10T14:14:48.871Z",
            "timeout": -1
        },
        "__v": 0,
        "parentFolder": "636cd1d2692344da47f3e2f0",
        "TreeResult": []
    }
]

Here is mongo play ground link: https://mongoplayground.net/p/M4pEB34Ozib

vamsi
  • 151
  • 3
  • 13