0.0.20 • Published 9 months ago

mongo-http v0.0.20

Weekly downloads
-
License
ISC
Repository
github
Last release
9 months ago

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

ParameterTypeDefault ValueDescription
filterobject{}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.
projectionobject{}A MongoDB Query Projection. Depending on the projection, the returned document will either omit specific fields or include only specified fields or values)

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
documentobject / nullIf a document is matched, an object is returnedIf not matched, a null is returned
errorerror / nullError 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

ParameterTypeDefault valueDescription
filterobject{}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.
projectionobject{}A MongoDB Query Projection. Depending on the projection, the returned document will either omit specific fields or include only specified fields or values)
sortobject{}A MongoDB Sort Expression. Matched documents are returned in ascending or descending order of the fields specified in the expression.
limitnumber1000The maximum number of matched documents to include in the returned result set. Each request may return up to 50,000 documents.
skipnumber0The number of matched documents to skip before adding matched documents to the result set.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
documentsarray of object(s) / empty arrayIf document(s) are matched, an array of object(s) is returnedIf no matches, an empty array is returned
errorerror / nullError 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

ParameterTypeDefault valueDescription
documentobject{}An EJSON document to insert into the collection.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
insertedIdstringID of the newly inserted document
errorerror / nullError 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

ParameterTypeDefault valueDescription
documentsarray of object(s)[]An array of one or more EJSON documents to insert into the collection.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
insertedIdsarray of string(s)_id values of all inserted documents as an array of strings
errorerror / nullError 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

ParameterTypeDefault valueDescription
filterobject{}A MongoDB Query Filter. The updateOne action modifies the first document in the collection that matches this filter.
updateobject{}A MongoDB Update Expression that specifies how to modify the matched document
upsertbooleanfalseThe 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

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
matchedCountnumberThe number of documents that the filter matched
modifiedCountnumberThe number of matching documents that were updated
upsertedIdstringID of the newly inserted document
errorerror / nullError 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

ParameterTypeDefault valueDescription
filterobject{}A MongoDB Query Filter. The updateMany action modifies all documents in the collection that match this filter.
updateobject{}A MongoDB Update Expression that specifies how to modify matched documents.
upsertbooleanfalseThe 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

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
matchedCountnumberThe number of documents that the filter matched
modifiedCountnumberThe number of matching documents that were updated
upsertedIdstringID of the newly inserted document
errorerror / nullError 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

ParameterTypeDefault valueDescription
filterobject{}A MongoDB Query Filter. The replaceOne action overwrites the first document in the collection that matches this filter.
replacementobject{}An EJSON document that overwrites the matched document.
upsertbooleanfalseThe upsert flag only applies if no documents match the specified filter. If true, the replaceOne action inserts the replacement document.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
matchedCountnumberThe number of documents that the filter matched
modifiedCountnumberThe number of matching documents that were updated
upsertedIdstringID of the newly inserted document
errorerror / nullError information

.deleteOne({ filter })

Example

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

Parameter

ParameterTypeDefault valueDescription
filterobject{}A MongoDB Query Filter. The deleteOne action deletes the first document in the collection that matches this filter.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
deletedCountnumberThe number of deleted documents
errorerror / nullError information

.deleteMany({ filter })

Example

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

Parameter

ParameterTypeDefault valueDescription
filterobject{}A MongoDB Query Filter. The deleteMany action deletes all documents in the collection that match this filter.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
deletedCountnumberThe number of deleted documents
errorerror / nullError 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

ParameterTypeDefault valueDescription
pipelinearray of objects[]A MongoDB Aggregation Pipeline.

Return

FieldTypeDescription
isSuccessbooleanWhether the database operation successful or not
documentsarray of object(s) / empty arrayIf document(s) are matched, an array of object(s) is returnedIf no matches, an empty array is returned
errorerror / nullError information
0.0.20

9 months ago

0.0.19

1 year ago

0.0.17

1 year ago

0.0.16

1 year ago

0.0.15

1 year ago

0.0.14

1 year ago

0.0.13

1 year ago

0.0.12

1 year ago

0.0.11

1 year ago

0.0.10

1 year ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago

1.0.0

2 years ago