I am creating a Google Doc from Apps Script as follows:
var newDoc = DocumentApp.create(docName);
I want this new document to be created in an existing folder in my drive. I tried the following way:
var dir = DriveApp.getFolderById("folder-id");
dir.addFile(newDoc);
But I get the error as:
ReferenceError: "DocsList" is not defined.
Is there any way to create a new document in my existing folder or move my file to an existing folder via Apps Script?
Folder.addFile()
requires that you pass it a File, but DocumentApp.create()
returns a Document. What you need to do is use newDoc.getId()
to get its unique identifier, and then use it in DriveApp.getFileById()
to properly move the file.
var newDoc = DocumentApp.create(docName); // Create a Document
var docFile = DriveApp.getFileById(newDoc.getId()); // Get Document as File
var dir = DriveApp.getFolderById("folder-id"); // Get the folder
dir.addFile(docFile); // Add the file to the folder
DriveApp.getRootFolder().removeFile(docFile); // Optionally remove the file from root
Please also note that Google Drive files can exist in multiple folders. So if you only want the file to be listed in the "folder-id" folder, then you'll need to remove it from the root folder where it was created by default.