How to generate a Google Document inside a specific folder using Apps Script

I’m new to Google Apps Script and I’m trying to figure out how to make a Google Doc inside a particular folder. I wrote this code but it’s not working:

function makeDocumentInFolder() {
    // Create the parent directory
    var parentDir = DriveApp.createFolder('ProjectFolder');
    // Try to make a Google Doc inside it
    var newDoc = parentDir.createFile('MyDocument','Sample content here',MimeType.GOOGLE_DOCS);
}

I keep getting an error message about invalid content type. The weird thing is that when I use JPEG or PLAIN_TEXT mime types, everything works fine. But when I try to create a Google Docs file, it fails.

I know that DocumentApp.create('DocumentName') works for creating docs in the root directory, but I need to put the document in a specific subfolder. What’s the right way to do this? Am I missing something about how Google Docs should be created in folders?

yea, this got me too when i started! you need to use DocumentApp.create() first, then call addToFolder() - way easier than moving files around. just do var doc = DocumentApp.create('MyDoc'); DriveApp.getFileById(doc.getId()).addToFolder(yourFolder); and you’re good to go.

You can’t use createFile() with the GOOGLE_DOCS mime type to make a Google Doc directly. Google Docs need to be created with DocumentApp first, then moved to your folder.

Here’s how to do it:

function makeDocumentInFolder() {
    var parentDir = DriveApp.createFolder('ProjectFolder');
    // Create the document first using DocumentApp
    var newDoc = DocumentApp.create('MyDocument');
    // Get the file reference from Drive
    var docFile = DriveApp.getFileById(newDoc.getId());
    // Move it to your target folder
    docFile.moveTo(parentDir);
}

This creates the doc in your root directory first, then moves it where you want it. I’ve used this approach tons of times for document automation - works every time. Google’s native file types (Docs, Sheets, Slides) all have their own creation methods and won’t work with DriveApp’s createFile.

This is a super common issue when you’re starting with Apps Script. The createFile() method wants raw file content, but Google Docs use a special internal format that won’t work with this approach.

I’ve found using addFolder() on the new document works way cleaner than moving files around:

function makeDocumentInFolder() {
    var parentDir = DriveApp.createFolder('ProjectFolder');
    var newDoc = DocumentApp.create('MyDocument');
    var docFile = DriveApp.getFileById(newDoc.getId());
    parentDir.addFile(docFile);
    DriveApp.getRootFolder().removeFile(docFile);
}

This copies the document to your target folder and removes it from root in one go. I like it because it’s more explicit about where the file ends up. Just remember - Google’s native formats need their specific App services for creation. DocumentApp for docs, SpreadsheetApp for sheets, etc.