how to setup initial data in mongodb-memory-server?

Viewed 2223

I am looking into using mongodb-memory-server: https://github.com/nodkz/mongodb-memory-server for integration/unit tests in a node application.

For a lot of the tests it would be neat (or even necessary) to have some existing data in the database before running the test. One way to populate the database would be to make a general script or function, that could create all the test documents, and call that script before each test case, but I am afraid the script will be messy, and it will be difficult to create all references between documents etc.

Therefore, I am trying to figure out if I can create a complete dump of a sandbox database (maybe a subset of our already existing production database) that I can initialize the mongodb-memory-server with before each test case?

Is that possible? and is there maybe a better way of doing this?

2 Answers

Got an answer on github: https://github.com/nodkz/mongodb-memory-server/issues/309

It turns out that there's no build in way to initialize the database with a given dbdump. It is suggested to make a script.

One hack though is to use the dbPath option, to control which folder the database is stored in, and then overwrite the folder.

there is option to set DB path that can help to restore and dump the data from  mongo-memory-server

  const mongoServer = await MongoMemoryServer.create(
    {
      instance: {
        // port: number, // by default choose any free port
        // ip: string, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0`,
        dbName: 'dbName', // by default '' (empty string)
        dbPath: './src/_db', // by default create in temp directory
        // storageEngine?: string, // by default `ephemeralForTest`, available engines: [ 'ephemeralForTest', 'wiredTiger' ]
        // replSet?: string, // by default no replica set, replica set name
        // auth?: boolean, // by default `mongod` is started with '--noauth', start `mongod` with '--auth'
        // args?: string[], // by default no additional arguments, any additional command line arguments for `mongod` `mongod` (ex. ['--notablescan'])
      },
      binary: {
        // version: string, // by default '5.0.8'
        downloadDir: './', // by default node_modules/.cache/mongodb-memory-server/mongodb-binaries
        // platform: string, // by default os.platform()
        // arch: string, // by default os.arch()
        // checkMD5: boolean, // by default false OR process.env.MONGOMS_MD5_CHECK
        // systemBinary: string, // by default undefined or process.env.MONGOMS_SYSTEM_BINARY
      },
    });

  const mongooseOpts = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  };

  global.ObjectId = mongoose.Types.ObjectId
  const uri = await mongoServer.getUri('dbName');
  console.log(uri);
  //  To connect with testing  db
  mongoose.connect(uri, mongooseOpts);
Related