NodeJS
Make sure you have activated the mongodb
instrument in your CodSpeed GitHub workflow.
Make sure you are using the minimum required version of the NodeJS integrations:
In-depth guides
To see complete guides of the different integrations, check out the pages below:
📄️ Vitest (recommended)
MongoDB instrument guide for NodeJS with Vitest
📄️ tinybench
MongoDB instrument guide for NodeJS with Tinybench
- Jest, not supported yet (coming soon)
Dynamically providing the connection string
Each integration exports a setupInstruments
function that can be used to dynamically setup the instruments.
This function takes the actual connection string as an argument and returns the patched connection string that should be used to connect to the database.
type SetupInstrumentsRequestBody = {
/**
* The full `MONGO_URL` that is usually used to connect to the database.
*/
mongoUrl: string;
};
type SetupInstrumentsResponse = {
/**
* The patched `MONGO_URL` that should be used to connect to the database.
*/
remoteAddr: string;
};
/**
* Dynamically setup the CodSpeed instruments.
*/
declare function setupInstruments(
body: SetupInstrumentsRequestBody
): Promise<SetupInstrumentsResponse>;
You can use this function to set up the instruments in your application:
import { setupInstruments, withCodSpeed } from "@codspeed/tinybench-plugin";
import { MongoDBContainer } from "@testcontainers/mongodb";
import { registerCatControllerBenches } from "cats/cats.controller.tinybench";
import { Bench } from "tinybench";
async function setupDatabase() {
const mongodbContainer = await new MongoDBContainer("mongo:7.0.5").start();
const mongoUrl =
mongodbContainer.getConnectionString() +
"/test?replicaSet=rs0&directConnection=true";
const { remoteAddr } = await setupInstruments({ mongoUrl });
process.env.MONGO_URL = remoteAddr;
}
const bench = withCodSpeed(new Bench());
(async () => {
await setupDatabase();
registerCatControllerBenches(bench);
await bench.run();
console.table(bench.table());
})();
The example above uses the testcontainers
library to start a MongoDB container and get the connection string.
Then, the setupInstruments
function is used to patch the connection string and set it as the MONGO_URL
environment variable.
Finally, the bench
is run as usual.
The setupInstruments
function should be called only once during the whole benchmark run, and before any connection to the database is established.
Otherwise, the CodSpeed MongoDB instrument will not be able to collect the metrics.