google-apps-scriptgoogle-drive-apigoogle-docs-api

DriveApp.File.getParents is not working as expected


MyDrive
|_ Client
|_ tpl
   |_ intake.doc

I'm trying to get a reference to the MyDrive folder.

  var tpl_intakeDoc = DriveApp.getFileById(docIDs.tpl_intake);
  var parent = tpl_intakeDoc.getParents()[0];
  Logger.log(parent.getName());

This gives me the following error:

TypeError: Cannot call method "getName" of undefined. (line 50, file "Code")

Similarly, trying to iterate through the parent folders (Client and tpl) only shows tpl for some reason.

  var parents = tpl_intakeDoc.getParents();
  while (parents.hasNext()) {
    var parents = parents.next();
    Logger.log(folder.getName());
  }

All that is logged is:

[19-06-14 04:14:11:764 MDT] tpl

where I would expect to see something like:

[19-06-14 04:14:11:764 MDT] tpl

[19-06-14 04:14:11:764 MDT] Client

What am I doing wrong?


Solution

  • If my understanding is correct, how about this answer? In this answer, your 2nd script was modified.

    Modification points:

    The flow of this script is as follows.

    1. Retrieve the parent folder of intake.doc.
      • tpl is retrieved.
    2. Retrieve the parent folder of tpl.
      • MyDrive is retrieved.
    3. Retrieve the folders under MyDrive.
      • Client and tpl are retrieved.

    Modified script:

    var tpl_intakeDoc = DriveApp.getFileById(docIDs.tpl_intake);
    var parent = tpl_intakeDoc.getParents(); // tpl
    if (parent.hasNext()) {
      var parentOnParent = parent.next().getParents(); // MyDrive
      if (parentOnParent.hasNext()) {
        var MyDrive = parentOnParent.next().getFolders();
        while (MyDrive.hasNext()) {
          var folder = MyDrive.next();
          Logger.log(folder.getName()) // tpl, Client
        }
      }
    }
    

    Note:

    References:

    If I misunderstood your question and this was not the direction you want, I apologize.