I’m writing an init script (e.g. /docker-entrypoint-initdb.d/init.js
) which will be executed by the mongo
Docker image when the container is first created. (See the docs for the image, "Initializing a fresh instance" section.)
Within this script, I need to open a file from disk (on the container), and then insert an object into the database with that file’s content as a property. Something like this:
import fs from "fs";
let data = fs.readFileSync("/path/to/somefile.txt", { encoding: "base64" });
db.example.files.insertOne({
filename: "somefile.txt",
data: Binary.createFromBase64(data),
});
But this script is written for NodeJS — how can I do the same in a plain JS script executed via MongoDB directly (e.g. mongosh -f init.js
)?
2
Answers
Your
init.js
script, with some minor changes, will work in MongoDB 6.0.15 & 7.0.9. Probably since the NodeJS environment is available during startup.TL;DR: Remove the
fs
import.Changes needed:
somefile.txt
, need to be mounted/linked indocker-compose
volumesfs
import is should be removed 🤔up
:TypeError: Cannot assign to read only property 'message' of object 'SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"' (1:0)
getSiblingDB
, otherwise it goes under thetest
and the collection name becomesexample.files
; unless that’s what you wanted.docker-compose.yml
init.js
Contents of somefile.txt:
Result in the DB after first startup:
For MongoDB 5.x and 4.x, this needs to be done in a Shell script, instead of JS. And you’ll need to use
BinData
with subtype 0, instead ofBinary.createFromBase64
. The final result is the same in the DB.docker-compose.yml
init.sh for MongoDB 5.x
init.sh for MongoDB 4.x, change the
mongosh
tomongo
:Contents of somefile.txt:
Result in the DB after first startup: