Gathering detailed insights and metrics for mongodb-memory-server-core
Gathering detailed insights and metrics for mongodb-memory-server-core
Gathering detailed insights and metrics for mongodb-memory-server-core
Gathering detailed insights and metrics for mongodb-memory-server-core
Manage & spin up mongodb server binaries with zero(or slight) configuration for tests.
npm install mongodb-memory-server-core
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,605 Stars
2,505 Commits
187 Forks
20 Watching
9 Branches
107 Contributors
Updated on 26 Nov 2024
TypeScript (92.31%)
JavaScript (7.37%)
CSS (0.29%)
Shell (0.02%)
Cumulative downloads
Total Downloads
Last day
2.8%
126,507
Compared to previous day
Last week
3.8%
633,048
Compared to previous week
Last month
5.2%
2,605,674
Compared to previous month
Last year
19.8%
28,256,863
Compared to previous year
This package spins up an actual/real MongoDB server programmatically from within nodejs, for testing or mocking during development. By default it holds the data in memory. A fresh spun up mongod
process takes about 7Mb of memory. The server will allow you to connect your favorite ODM or client library to the MongoDB server and run integration tests isolated from each other.
On install, this package downloads the latest MongoDB binaries and saves them to a cache folder. (only mongodb-memory-server-core
does not download on postinstall
)
On starting a new instance of the memory server, if the binary cannot be found, it will be auto-downloaded (if RUNTIME_DOWNLOAD
option is truthy), thus the first run may take some time. All further runs will be fast, because they will use the downloaded binaries.
This package automatically downloads binaries from https://fastdl.mongodb.org/ according to your operating system. You can see all available versions for Linux (Ubuntu, RHEL, Debian, SUSE, Amazon), OSX, and Windows.
If your network is behind a proxy, make sure that it is configured through the
HTTPS_PROXY
orHTTP_PROXY
environment variable.
Every MongoMemoryServer
instance creates and starts a fresh MongoDB server on some free port. You may start up several mongod
simultaneously. When you terminate your script or call stop()
, the MongoDB server(s) will be automatically shutdown.
Works perfectly with any CI runner that can run NodeJS applications.
Table of Contents generated with DocToc
This tool provides three packages for different purposes:
mongodb-memory-server
, mongodb-memory-server-global-*
)mongodb-memory-server-core
)Choose any package, because they are the same. They differ only in the default configuration, which you may override (see section Available options).
And one of those (on Linux):
lsb-core
installed (or any that provides the lsb_release
command)/etc/os-release
file that is compliant to the OS-Release Spec/etc/*-release
file that is compliant to the OS-Release Spec (and does not include lsb
)On Linux, you will also need libcurl4
(or libcurl3
on some older distro versions). This will probably only be an issue on "slim" Docker images.
Choose the right package for the task
The default behavior is that version 7.0.14
for your OS will be downloaded. By setting Environment variables you are able to specify which version and binary will be downloaded:
1export MONGOMS_DOWNLOAD_URL=https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1804-4.2.8.tgz 2export MONGOMS_VERSION=4.2.8
A Normal Server can be easily started with:
1import { MongoMemoryServer } from 'mongodb-memory-server'; 2 3// This will create an new instance of "MongoMemoryServer" and automatically start it 4const mongod = await MongoMemoryServer.create(); 5 6const uri = mongod.getUri(); 7 8// The Server can be stopped again with 9await mongod.stop();
All options with ?
are optional, some options upon specified are required.
1const mongod = new MongoMemoryServer({ 2 instance?: { 3 port?: number, // by default choose any free port 4 ip?: string, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0`, 5 dbName?: string, // by default '' (empty string) 6 dbPath?: string, // by default create in temp directory 7 storageEngine?: string, // by default `ephemeralForTest`(unless mongodb 7.0.0, where its `wiredTiger`), available engines: [ 'ephemeralForTest', 'wiredTiger' ] 8 replSet?: string, // by default no replica set, replica set name 9 args?: string[], // by default no additional arguments, any additional command line arguments for `mongod` `mongod` (ex. ['--notablescan']) 10 auth?: boolean, // add "--auth" argument, dont use this directly use top-level "auth" 11 }, 12 binary?: { 13 version?: string, // by default '7.0.14' 14 downloadDir?: string, // see the documentation on what is chosen by default https://typegoose.github.io/mongodb-memory-server/docs/api/config-options#download_dir 15 platform?: string, // by default os.platform() 16 arch?: string, // by default os.arch() 17 checkMD5?: boolean, // by default false OR process.env.MONGOMS_MD5_CHECK 18 systemBinary?: string, // by default undefined or process.env.MONGOMS_SYSTEM_BINARY 19 }, 20 // using "auth" will manage "instance.auth" 21 auth?: { 22 // enable needs to be set to "true", otherwise automatic user creation is by default disabled 23 enable?: boolean, // enable automatic user creation 24 customRootName?: string, // by default "mongodb-memory-server-root" 25 customRootPwd?: string, // by default "rootuser" 26 force?: boolean, // force creation of users 27 keyfileContent?: string, // by default "0123456789" (only useful for replsets) 28 extraUsers?: [{ 29 // see mongodb documentation https://docs.mongodb.com/manual/reference/method/db.createUser/#definition) 30 createUser: string, // user name 31 pwd: string, // user password 32 roles: UserRoles[], // user roles 33 database?: string, // which database the user is created on 34 customData?: Record<string, any>, // any arbitrary information, see mongodb documentation 35 mechanisms?: ('SCRAM-SHA-1' | 'SCRAM-SHA-256')[], 36 authenticationRestrictions?: { 37 clientSource?: string; 38 serverAddress?: string; 39 }[], 40 digestPassword?: boolean, 41 }], 42 }, 43});
A ReplicaSet can be easily started with:
1import { MongoMemoryReplSet } from 'mongodb-memory-server'; 2 3// This will create an new instance of "MongoMemoryReplSet" and automatically start all Servers 4const replset = await MongoMemoryReplSet.create({ replSet: { count: 4 } }); // This will create an ReplSet with 4 members 5 6const uri = replset.getUri(); 7 8// The ReplSet can be stopped again with 9await replset.stop();
All options are optional.
1const replSet = new MongoMemoryReplSet({ 2 binary: binaryOpts, // same as for MongoMemoryServer 3 instanceOpts: [ 4 { 5 args, // any additional instance specific args 6 port, // port number for the instance 7 dbPath, // path to database files for this instance 8 storageEngine, // same storage engine options 9 }, 10 // each entry will result in a MongoMemoryServer (replSet.count will not limit the amount spawned by "instanceOpts") 11 ], 12 // unless otherwise noted below these values will be in common with all instances spawned: 13 replSet: { 14 name, // replica set name (default: 'testset') 15 auth?: boolean | AutomaticAuth, // enable auth, for options see #available-options-for-mongomemoryserver 16 args, // any args specified here will be combined with any per instance args from `instanceOpts` 17 count, // number of additional `mongod` processes to start (will not start any extra if instanceOpts.length > replSet.count); (default: 1) 18 dbName, // default database for db URI strings 19 ip, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0` 20 spawn, // spawn options when creating the child processes 21 storageEngine, // default storage engine for instance. (Can be overridden per instance) 22 configSettings: { 23 // Optional settings for 'replSetInitiate' command. See https://docs.mongodb.com/manual/reference/command/replSetInitiate/ 24 chainingAllowed: boolean, // When true it allows secondary members to replicate from other secondary members. When false, secondaries can replicate only from the primary. 25 heartbeatTimeoutSecs: number, // Number of seconds that the replica set members wait for a successful heartbeat from each other. If a member does not respond in time, other members mark the delinquent member as inaccessible. 26 heartbeatIntervalMillis: number, // The frequency in milliseconds of the heartbeats. 27 electionTimeoutMillis: number, // The time limit in milliseconds for detecting when a replica set’s primary is unreachable. 28 catchUpTimeoutMillis: number, // Time limit for a newly elected primary to sync (catch up) with the other replica set members that may have more recent writes. 29 }, 30 }, 31});
Documentation of Config Options
A example test file for a single MongoMemoryServer within jest.
A example test file for multiple MongoMemoryServer within jest.
A example test file for a single MongoMemoryReplSet within jest.
1// assuming mongoose@6.x 2import mongoose from 'mongoose'; 3import { MongoMemoryServer } from 'mongodb-memory-server'; 4 5const mongoServer = await MongoMemoryServer.create(); 6 7(async () => { 8 await mongoose.connect(mongoServer.getUri(), { dbName: "verifyMASTER" }); 9 10 // your code here 11 12 await mongoose.disconnect(); 13})();
Documentation for Test Runner Integration Examples
There isn't currently an official MongoDB release for alpine linux. This means that we can't pull binaries for Alpine
(or any other platform that isn't officially supported by MongoDB), but you can use a Docker image that already has mongod
built in and then set the MONGOMS_SYSTEM_BINARY
variable to point at that binary. This should allow you to use mongodb-memory-server
on any system on which you can install mongod manually.
The Debug mode can be enabled with an Environment-Variable or in the package.json "config" section:
1MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"
or
1{ 2 "config": { 3 "mongodbMemoryServer": { 4 "debug": "1", // also available case-insensitive values: "on" "yes" "true" 5 } 6 } 7}
Also see the Enable Debug Mode Guide.
Contributing Guidelines are setup in CONTRIBUTING
To ask questions or just talk with us, join our Discord Server.
Inspired by alternative runners for mongodb-prebuilt:
This project exists thanks to all the people who contribute.
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
MIT
No vulnerabilities found.
No security vulnerabilities found.
mongodb-memory-server
MongoDB Server for testing (auto-download latest version). The server will allow you to connect your favourite ODM or client library to the MongoDB Server and run parallel integration tests isolated from each other.
mongodb-memory-server-global
MongoDB Server for testing (auto-download latest version to ~/.cache/mongodb-binaries).
@steedos/mongodb-memory-server-core
MongoDB Server for testing (core package, without autodownload). The server will allow you to connect your favourite ODM or client library to the MongoDB Server and run parallel integration tests isolated from each other.
mongodb-core
Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications