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

mongo-http

v0.0.20

Published

A thin wrapper on Mongodb Atlas Data API using native fetch API

Downloads

34

Readme

mongo-http.js

About

mongo-http.js flow

A thin wrapper on Mongodb Atlas Data API using native fetch API. This library serves the usecase where

  • TCP connections over Mongodb Atlas is not possible (e.g. Serverless runtime like Cloudflare Workers), while still wanting to use similar MongoDB driver syntax.
  • It can also be used in serverless runtimes which the reuse of a MongoDB connection may not always be available or require manual caching
  • Sadly, it cannot be used in the browser side yet, due to CORS. Here is a thread to request the CORS feature

Table of Contents

  1. About
  2. Setup
    1. Get the App ID and API Key from Mongodb Atlas
    2. Installation
    3. Initialization
  3. API
    1. findOne
    2. find
    3. insertOne
    4. insertMany
    5. updateOne
    6. updateMany
    7. replaceOne
    8. deleteOne
    9. deleteMany
    10. aggregate

Setup

1. Setup MongoDB Atlas to get the App ID and API Key (and App Region)

Follow MongoDB Atlas tutorial.

Get the App ID here

Screenshot 2022-11-20 at 2 25 46 PM

🚨 Importart 🚨: If you select "Local (single region)" when you enable Data API

Screenshot 2023-08-27 at 11 13 25 PM

Make sure to pass the App Region as well!

Screenshot 2023-08-27 at 11 14 29 PM

And Get the API Key here

Screenshot 2022-11-20 at 2 27 12 PM

2. Installation

npm install mongo-http --save

3. Initialization

Depending on your needs, you can either initialize a client, database, or collection

You can initialize a client for connecting to multiple databases

import { initClient } from 'mongo-http';

const client = initClient({
    appId: process.env.appId,
    apiKey: process.env.apiKey,
    // Important! Pass `appRegion` if you deploy Data API as "Local (single region)"
    // See above "1. Setup MongoDB Atlas to get the App ID and API Key (and App Region)"
    appRegion: process.env.appRegion,
});

const db = client.database({ databaseName: process.env.databaseName });

const result = await db.collection('articles').find({
    filter: {
        $or: [{ categories: { $in: ['javascript', 'reactjs', 'nodejs', 'mongodb'] } }],
    },
});

... Or, Initialize a database

import { initDatabase } from 'mongo-http';

const db = initDatabase({
    appId: process.env.appId,
    apiKey: process.env.apiKey,
    // Important! Pass `appRegion` if you deploy Data API as "Local (single region)"
    // See above "1. Setup MongoDB Atlas to get the App ID and API Key (and App Region)"
    appRegion: process.env.appRegion,
    databaseName: process.env.databaseName || '',
});

const result = await db.collection('articles').find({});

... Or, Initialize a collection

import { initCollection } from 'mongo-http';

const articlesCollection = initCollection({
    appId: process.env.appId,
    apiKey: process.env.apiKey,
    // Important! Pass `appRegion` if you deploy Data API as "Local (single region)"
    // See above "1. Setup MongoDB Atlas to get the App ID and API Key (and App Region)"
    appRegion: process.env.appRegion,
    databaseName: process.env.databaseName,
    collectionName: 'articles',
});

const result = await articlesCollection.find({});

API

.findOne({ filter, projection })

Example

const { isSuccess, document, error } = await db.collection('articles').findOne({
    filter: {
        $or: [{ creator: 'Patrick Chiu' }, { title: 'Migrating a Node.js App to Cloudflare Workers From Heroku' }],
    },
    projection: { title: 1, creator: 1, guid: 1, categories: 1 },
});

Parameter

| Parameter | Type | Default Value | Description | | ---------- | ------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | filter | object | {} | A MongoDB Query Filter. The findOne action returns the first document in the collection that matches this filter.If you do not specify a filter, the action matches all document in the collection. | | projection | object | {} | A MongoDB Query Projection. Depending on the projection, the returned document will either omit specific fields or include only specified fields or values) |

Return

| Field | Type | Description | | --------- | ------------- | --------------------------------------------------------------------------------------- | | isSuccess | boolean | Whether the database operation successful or not | | document | object / null | If a document is matched, an object is returnedIf not matched, a null is returned | | error | error / null | Error information |

.find({ filter, projection, sort, limit, skip })

Example

const { isSuccess, documents, error } = await db.collection('articles').find({
    filter: {
        $or: [{ categories: { $in: ['javascript', 'nodejs'] } }],
    },
    projection: { title: 1, creator: 1, guid: 1, categories: 1 },
    sort: { createdAt: -1 },
    limit: 50,
    skip: 100,
});

Parameter

| Parameter | Type | Default value | Description | | ---------- | ------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | filter | object | {} | A MongoDB Query Filter. The find action returns documents in the collection that match this filter.If you do not specify a filter, the action matches all document in the collection.If the filter matches more documents than the specified limit, the action only returns a subset of them. You can use skip in subsequent queries to return later documents in the result set. | | projection | object | {} | A MongoDB Query Projection. Depending on the projection, the returned document will either omit specific fields or include only specified fields or values) | | sort | object | {} | A MongoDB Sort Expression. Matched documents are returned in ascending or descending order of the fields specified in the expression. | | limit | number | 1000 | The maximum number of matched documents to include in the returned result set. Each request may return up to 50,000 documents. | | skip | number | 0 | The number of matched documents to skip before adding matched documents to the result set. |

Return

| Field | Type | Description | | --------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------ | | isSuccess | boolean | Whether the database operation successful or not | | documents | array of object(s) / empty array | If document(s) are matched, an array of object(s) is returnedIf no matches, an empty array is returned | | error | error / null | Error information |

.insertOne(document)

Example

const { isSuccess, insertedId, error } = await db.collection('tags').insertOne({
    cachedAt: '2022-11-25T17:44:59.981+00:00',
    tags: ['startup', 'programming', 'digital-nomad', 'passive-income', 'python'],
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ------ | ------------- | ----------------------------------------------------------------------------------------------------------------------- | | document | object | {} | An EJSON document to insert into the collection. |

Return

| Field | Type | Description | | ---------- | ------------ | ------------------------------------------------ | | isSuccess | boolean | Whether the database operation successful or not | | insertedId | string | ID of the newly inserted document | | error | error / null | Error information |

.insertMany(documents)

Example

const { isSuccess, insertedIds, error } = await db.collection('tags').insertMany([
    {
        date: '2022-11-01T00:00:00.000+00:00',
        tags: ['startup', 'programming', 'digital-nomad', 'passive-income', 'python'],
    },
    {
        date: '2022-12-01T00:00:00.000+00:00',
        tags: ['goblin-mode', 'new-year', 'economic-crisis'],
    },
]);

Parameter

| Parameter | Type | Default value | Description | | --------- | ------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | documents | array of object(s) | [] | An array of one or more EJSON documents to insert into the collection. |

Return

| Field | Type | Description | | ----------- | ------------------ | ------------------------------------------------------------- | | isSuccess | boolean | Whether the database operation successful or not | | insertedIds | array of string(s) | _id values of all inserted documents as an array of strings | | error | error / null | Error information |

.updateOne({ filter, update, upsert })

Example

const { isSuccess, matchedCount, modifiedCount, upsertedId, error } = await db.collection('tags').updateOne({
    filter: {
        _id: { $oid: '638199c045955b5e9701be1f' },
    },
    update: {
        date: '2022-11-25T00:00:00.000+00:00',
        tags: ['startup', 'programming', 'digital-nomad', 'passive-income', 'python', 'something-else'],
    },
    upsert: true,
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | filter | object | {} | A MongoDB Query Filter. The updateOne action modifies the first document in the collection that matches this filter. | | update | object | {} | A MongoDB Update Expression that specifies how to modify the matched document | | upsert | boolean | false | The upsert flag only applies if no documents match the specified filter. If true, the updateOne action inserts a new document that matches the filter with the specified update applied to it. |

Return

| Field | Type | Description | | ------------- | ------------ | -------------------------------------------------- | | isSuccess | boolean | Whether the database operation successful or not | | matchedCount | number | The number of documents that the filter matched | | modifiedCount | number | The number of matching documents that were updated | | upsertedId | string | ID of the newly inserted document | | error | error / null | Error information |

.updateMany({ filter, update, upsert })

Example

const { isSuccess, matchedCount, modifiedCount, upsertedId, error } = await db.collection('users').updateMany({
    filter: {
        lastLoginAt: { $lt: '2023-01-01' },
    },
    update: {
        isActive: false,
    },
    upsert: true,
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | filter | object | {} | A MongoDB Query Filter. The updateMany action modifies all documents in the collection that match this filter. | | update | object | {} | A MongoDB Update Expression that specifies how to modify matched documents. | | upsert | boolean | false | The upsert flag only applies if no documents match the specified filter. If true, the updateMany action inserts a new document that matches the filter with the specified update applied to it. |

Return

| Field | Type | Description | | ------------- | ------------ | -------------------------------------------------- | | isSuccess | boolean | Whether the database operation successful or not | | matchedCount | number | The number of documents that the filter matched | | modifiedCount | number | The number of matching documents that were updated | | upsertedId | string | ID of the newly inserted document | | error | error / null | Error information |

.replaceOne({ filter, replacement, upsert })

Example

const { isSuccess, matchedCount, modifiedCount, upsertedId, error } = await db.collection('tags').replaceOne({
    filter: {
        _id: { $oid: '638199c045955b5e9701be1f' },
    },
    replacement: {
        date: '2022-11-25T00:00:00.000+00:00',
        tags: ['startup', 'programming', 'digital-nomad', 'passive-income', 'python', 'something-else'],
    },
    upsert: true,
});

Parameter

| Parameter | Type | Default value | Description | | ----------- | ------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | filter | object | {} | A MongoDB Query Filter. The replaceOne action overwrites the first document in the collection that matches this filter. | | replacement | object | {} | An EJSON document that overwrites the matched document. | | upsert | boolean | false | The upsert flag only applies if no documents match the specified filter. If true, the replaceOne action inserts the replacement document. |

Return

| Field | Type | Description | | ------------- | ------------ | -------------------------------------------------- | | isSuccess | boolean | Whether the database operation successful or not | | matchedCount | number | The number of documents that the filter matched | | modifiedCount | number | The number of matching documents that were updated | | upsertedId | string | ID of the newly inserted document | | error | error / null | Error information |

.deleteOne({ filter })

Example

const { isSuccess, deletedCount, error } = await db.collection('tags').deleteOne({
    filter: {
        date: '2022-12-01T00:00:00.000+00:00',
    },
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | filter | object | {} | A MongoDB Query Filter. The deleteOne action deletes the first document in the collection that matches this filter. |

Return

| Field | Type | Description | | ------------ | ------------ | ------------------------------------------------ | | isSuccess | boolean | Whether the database operation successful or not | | deletedCount | number | The number of deleted documents | | error | error / null | Error information |

.deleteMany({ filter })

Example

const { isSuccess, deletedCount, error } = await db.collection('tags').deleteMany({
    filter: {
        date: { $gte: '2022-12-01' },
    },
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | filter | object | {} | A MongoDB Query Filter. The deleteMany action deletes all documents in the collection that match this filter. |

Return

| Field | Type | Description | | ------------ | ------------ | ------------------------------------------------ | | isSuccess | boolean | Whether the database operation successful or not | | deletedCount | number | The number of deleted documents | | error | error / null | Error information |

.aggregate({ pipeline })

Example

const { isSuccess, documents, error } = await db.collection('users').aggregate({
    pipeline: [
        { $match: { userId: 'f95cfc82f512' } },
        {
            $lookup: {
                from: 'notifications',
                localField: 'userId',
                foreignField: 'userId2',
                as: 'notification',
            },
        },
        { $unwind: '$notification' },
    ],
});

Parameter

| Parameter | Type | Default value | Description | | --------- | ---------------- | ------------- | ------------------------------------------------------------------------------------------------- | | pipeline | array of objects | [] | A MongoDB Aggregation Pipeline. |

Return

| Field | Type | Description | | --------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------ | | isSuccess | boolean | Whether the database operation successful or not | | documents | array of object(s) / empty array | If document(s) are matched, an array of object(s) is returnedIf no matches, an empty array is returned | | error | error / null | Error information |