Skip to content

patrick-kw-chiu/mongo-http.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mongo-http.js

About

mongo-http.js icon

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

mongo-http.js flow

Quick example

import { initDatabase } from 'mongo-http';

const db = initDatabase({
    appId: process.env.appId,
    apiKey: process.env.apiKey,
    appRegion: process.env.appRegion,
    databaseName: process.env.databaseName,
});

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,
});

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 returned
If 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 returned
If 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 returned
If no matches, an empty array is returned
error error / null Error information