Skip to content
Latchkey

mongosh --file: Run a MongoDB Script in CI

mongosh --file script.js executes a JavaScript file against the database and exits with its status.

Migrations and seed data belong in a versioned .js file, not inline. --file runs that file the same way locally and in CI.

What it does

mongosh --file (or a trailing positional path) loads and runs a JavaScript file against the connected database, then exits. The process exit code reflects whether the script threw, so a failing migration fails the CI step. This replaces the legacy mongo script.js invocation.

Common usage

Terminal
mongosh "mongodb://localhost:27017/app" --quiet --file ./db/seed.js
# positional form (path after the connection string)
mongosh "mongodb://localhost:27017/app" --quiet ./db/migrate.js
# pass an argument the script reads from process.argv
mongosh --quiet --eval 'const ENV="ci"' --file ./db/seed.js

Options

FlagWhat it does
--file <path>Run the JavaScript file and exit
<path>Positional script path also works
--quietSuppress banner so script output is clean
--eval ... --file ...Define variables with --eval before the file runs
--norcSkip the user rc file for reproducible runs

In CI

Make the script throw on failure (use throw new Error(...)) so mongosh exits non-zero and the job fails loudly. mongosh runs scripts in a Node-like environment, so top-level await works; the legacy mongo shell did not support it, a common reason an old script breaks after the upgrade.

Common errors in CI

"Error: ENOENT: no such file or directory" means the --file path is wrong relative to the working directory; CI checkout paths differ from local. "ReferenceError: print is not defined" or similar means you ran it through node instead of mongosh. An uncaught exception prints a stack and exits 1, which is what you want for a failing migration.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →