npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@storyous/mongodb

v1.10.0

Published

## Usage of MongoClient

Downloads

109

Readme

mongodb

Usage of MongoClient

import { mongoClient } from '@storyous/mongodb';

// Initialize and connect MongoDB
mongoClient.init('mongodb://127.0.0.1:27017');
await mongoClient.getClient().connect();

// Useage of MongoClient
const user = mongoClient.getClient().db('test').collection('users').find();

// Close current connection
await mongoClient.getClient().close();

Usage of getMongoConfig

import { getMongoConfig, mongoClient } from '@storyous/mongodb';

// Set following env variables:
// DOCUMENTDB_ENGINE="mongodb" (or "documentdb")
// DOCUMENTDB_ENDPOINT="127.0.0.1"
// DOCUMENTDB_USER="user"
// DOCUMENTDB_PASSWORD="password"
//
// Optional env variables (and default values)
// DOCUMENTDB_DATABASE=""
// DOCUMENTDB_PORT="27017"
// DOCUMENTDB_PROTOCOL="mongodb"
// DOCUMENTDB_QUERY="?retryWrites=false"

// Get config
const config = {
    database: {
        ...getMongoConfig(),
    }
};

// Initialize and connect MongoDB
mongoClient.init(config.database.mongodbUrl, config.database.mongoOptions);

You can also use custom prefix for environment variables (e.g. MY_DB_ENGINE, MY_DB_ENDPOINT, ...):

getMongoConfig('MY_DB');

Usage of MongoLocker

import { getMongoLocker, mongoLocker } from '@storyous/mongodb';

// default mongoLocker instance
const locker = mongoLocker();
const callback = () => {}
const result1 = await locker('someKey', callback);

// custom mongoLocker instance
const locker = getMongoLocker('nameOfMyCollecrion');
const callback = () => {}
const result1 = await locker('someKey', callback);

Usage of Fixtures

import { fixtures, mongoClient } from '@storyous/mongodb';

const collection = mongoClient.getClient().db().collection('currency');
const currencyFixtures = [
    { _id: new ObjectId(), name: 'CZK' },
    { _id: new ObjectId(), name: 'EUR' },
];
await fixtures.ensureInCollection(currencyFixtures, collection);

Usage of WithTransaction

import { mongoClient, withTransaction } from '@storyous/mongodb';

const collection = mongoClient.getClient().db().collection('currency');
const returnValue = await withTransaction(async (session) => {
    await testCollection.insertOne({}, { session });
    
    return true;
});

Usage of AppData

import { appData } from '@storyous/mongodb';

const testDocument = { _id: new ObjectId() };
await appData.ensureDocumentExists(testDocument);
await appData.updateDocument(testDocument._id, { $set: { foo: 'bar' } });
await appData.getDocument(testDocument._id);

Usage of Migrations

Generation of new migration

Add this target into your package.json:

"migrate:create": "migrate create --migrations-dir ./migrations --template-file ./node_modules/@storyous/mongodb/lib/migrations/template.ts"

Run target by npm:

npm run migrate:create nameOfMyMigration

Run migration

import { runMigrations } from '@storyous/mongodb';

await runMigrations(createLogger(), `${__dirname}/migrations`, {
     safeMigration: config.mongoSafeMigration
});

note: The "safeMigration" needs to be false on testing and localhost environment. And it should be true on TEST and PROD.

safeMigration: true does not run migration if it does not find any migration data in database or it is trying to run all migrations from beginning.

On first deploy to TEST/PROD you need to setup it to "false". Then it should be changed to "true"

Reason: Once it happened on production that the migrations history were erased for unknown reason and the migration started again - which caused a lot of issues. safeMigration: true should prevent it.