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
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,
});
Follow MongoDB Atlas tutorial.
Make sure to pass the App Region as well!
npm install mongo-http --save
Depending on your needs, you can either initialize a client, database, or collection
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'] } }],
},
});
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({});
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({});
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 | 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) |
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 |
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 | 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. |
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 |
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 | Type | Default value | Description |
---|---|---|---|
document | object | {} | An EJSON document to insert into the collection. |
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 |
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 | Type | Default value | Description |
---|---|---|---|
documents | array of object(s) | [] | An array of one or more EJSON documents to insert into the collection. |
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 |
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 | 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. |
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 |
const { isSuccess, matchedCount, modifiedCount, upsertedId, error } = await db.collection('users').updateMany({
filter: {
lastLoginAt: { $lt: '2023-01-01' },
},
update: {
isActive: false,
},
upsert: true,
});
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. |
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 |
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 | 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. |
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 |
const { isSuccess, deletedCount, error } = await db.collection('tags').deleteOne({
filter: {
date: '2022-12-01T00:00:00.000+00:00',
},
});
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. |
Field | Type | Description |
---|---|---|
isSuccess | boolean | Whether the database operation successful or not |
deletedCount | number | The number of deleted documents |
error | error / null | Error information |
const { isSuccess, deletedCount, error } = await db.collection('tags').deleteMany({
filter: {
date: { $gte: '2022-12-01' },
},
});
Parameter | Type | Default value | Description |
---|---|---|---|
filter | object | {} | A MongoDB Query Filter. The deleteMany action deletes all documents in the collection that match this filter. |
Field | Type | Description |
---|---|---|
isSuccess | boolean | Whether the database operation successful or not |
deletedCount | number | The number of deleted documents |
error | error / null | Error information |
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 | Type | Default value | Description |
---|---|---|---|
pipeline | array of objects | [] | A MongoDB Aggregation Pipeline. |
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 |