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

masfana-mongodb-api-sdk

v1.0.5

Published

A TypeScript SDK for MongoDB Atlas Data API with query operator IntelliSense.

Downloads

1,884

Readme

MasFana MongoDB Data API SDK

A TypeScript SDK for interacting with MongoDB Atlas Data API with full IntelliSense support for query operators.

Alternative for Native MongoDB SDK

Installation


npm  install  masfana-mongodb-api-sdk

Requirements

Example

Getting Started

Step 1: Setting Up MongoDB Atlas Data API

To use this SDK, you need to enable the Data API in your MongoDB Atlas cluster. Here’s a brief guide:

  1. Log in to your MongoDB Atlas account.

  2. Go to App Services and click Create new application.

  3. Enable the Data API for your application.

  4. Copy the App ID and API Key from the Data API section.

Step 2: Environment Configuration

To use the SDK, you'll need to configure the MongoDB environment variables in your project. Create a .env file in the root of your project:


touch  .env

Step 3: Setting Up Your TypeScript Project

If you're using TypeScript, ensure that you have a basic tsconfig.json set up:


{

"compilerOptions": {

"target": "ES6",

"module": "CommonJS",

"outDir": "./dist",

"strict": true,

"esModuleInterop": true

},

"include": ["src/**/*.ts"],

"exclude": ["node_modules"]

}

Create a src/index.ts file where you'll write your code.

Step 4: Using the SDK

  1. Import the SDK and define the types for your MongoDB documents.

  2. Initialize the MongoDB API with environment variables.

  3. Use the provided CRUD methods (findOne, find, insertOne, updateOne, deleteOne, aggregate).

Example


import { MongoDBAPI } from  "mongodb-data-api-sdk";

import  *  as  dotenv  from  "dotenv";

dotenv.config();

  

// Define the type of the documents in your MongoDB collection

type  Task = {

text: string;

status: string;

completedAt?: Date;

};

  

// Initialize the MongoDB API SDK with environment variables

const  env = {

MONGO_API_URL:  process.env.MONGO_API_URL!,

MONGO_API_KEY:  process.env.MONGO_API_KEY!,

DATABASE:  process.env.DATABASE!,

COLLECTION:  process.env.COLLECTION!,

DATA_SOURCE:  process.env.DATA_SOURCE!

};

  

const  mongoAPI = new  MongoDBAPI<Task>(env);

  

// Example usage of the SDK

async  function  run() {

try {

// Find a single document where the task status is "complete"

const  task = await  mongoAPI.findOne({ status: { $eq:  "complete" } });

console.log("Found task:", task);

  

// Insert a new task

const  insertResult = await  mongoAPI.insertOne({ text:  "Clean the kitchen", status:  "open" });

console.log("Inserted task with ID:", insertResult.insertedId);

  

// Find all tasks with status "open", sort by `completedAt` field, and return only `text` and `status` fields

const  tasks = await  mongoAPI.find(

{ status: { $eq:  "open" } },

{ text:  1, status:  1 },

{ completedAt: -1 },

10  // Limit to 10 results

);

console.log("Found tasks:", tasks);

  

// Update a task to mark it as "complete"

const  updateResult = await  mongoAPI.updateOne({ text:  "Clean the kitchen" }, { status:  "complete" });

console.log("Updated task:", updateResult);

  

// Delete a task

const  deleteResult = await  mongoAPI.deleteOne({ text:  "Clean the kitchen" });

console.log("Deleted task:", deleteResult.deletedCount);

  

} catch (error) {

console.error("Error:", error);

}

}

  

run();

Step 5: Running Your Application

To run the example code, ensure you’ve set up your TypeScript project and compiled your code:


# Install dependencies

npm  install

  

# Compile TypeScript code

npm  run  build

  

# Run the compiled JavaScript code

node  dist/index.js

  

### CRUD Operations Overview
  1. Find One Document

const  task = await  mongoAPI.findOne({ status: { $eq:  "complete" } });
  1. Find Many Documents

const  tasks = await  mongoAPI.find(

{ status: { $eq:  "open" } }, // Filter

{ text:  1, status:  1 }, // Projection (fields to include)

{ completedAt: -1 }, // Sort by completedAt descending

10  // Limit results to 10

);
  1. Insert One Document

const  insertResult = await  mongoAPI.insertOne({ text:  "Buy groceries", status:  "open" });
  1. Update One Document

const  updateResult = await  mongoAPI.updateOne({ text:  "Buy groceries" }, { status:  "complete" });
  1. Delete One Document

const  deleteResult = await  mongoAPI.deleteOne({ text:  "Buy groceries" });

MongoDB Query Operators Supported

Here are some common MongoDB query operators supported by this SDK:

  • $eq: Matches values that are equal to a specified value.

  • $ne: Matches values that are not equal to a specified value.

  • $gt: Matches values that are greater than a specified value.

  • $gte: Matches values that are greater than or equal to a specified value.

  • $lt: Matches values that are less than a specified value.

  • $lte: Matches values that are less than or equal to a specified value.

  • $in: Matches any of the values specified in an array.

  • $nin: Matches none of the values specified in an array.

  • $exists: Matches documents where the field exists.

TypeScript Support

The SDK is fully type-safe, so your code will have IntelliSense support for query operators and MongoDB operations. Here's an example of how IntelliSense helps you with MongoDB operators like $eq, $gt, and more:


const  filter = {

status: { $eq:  "complete" },

completedAt: { $gt:  new  Date("2023-01-01") }

};