Warning
This project will no longer be supported on September 15, 2024 due to developers losing interest in MongoDB.
Simple
ORM? ODM? Driver? You don't need them. We already have the most powerful API on the web—the Fetch API.
Easy and Powerful
This handler reduces the verbosity that comes with the MongoDB Data API. You don't need to serialize queries with
JSON.stringify()or deserialize query results with.json().We don't abstract away the beauty of the MongoDB Data API.
Write your queries as you like, and we will send them to MongoDB.
For setup, please refer to Getting Started with Deno & MongoDB.
For more information about the MongoDB Data API, please see the official documentation.
Caution
Available for Node version 18 and above
NPM:
npx jsr add @kokomi/mongo-request-handlerPNPM:
pnpm dlx jsr add @kokomi/mongo-request-handlerDeno:
deno add @kokomi/mongo-request-handlerYarn:
yarn dlx jsr add @kokomi/mongo-request-handlerBun:
bunx jsr add @kokomi/mongo-request-handlerDefine a database configuration object:
You can easily get this data with MongoDB Compass. For more information, please watch the video Getting Started with Deno & MongoDB.
import{createSendDBRequestFunction,typeDatabaseConfig,MongoDBRequest,}from"@kokomi/mongo-request-handler";constconfig: DatabaseConfig={baseUrl: "https://data.mongodb-api.com/app/data-<APP_ID>/endpoint/data/v1",dataSource: "Cluster0",database: "myDatabase",apiKey: "your-api-key",};
Create a function to send the request:
constsendDBRequest=createSendDBRequestFunction(config);
Create a request:
Making a request is simple.
Create a request object:
constdbRequest=newMongoDBRequest();
Add a endpoint:
Sets the endpoint following the base path for the MongoDB Data API.
dbRequest.endpoint="/find";
Add a query:
Set the query to send to that endpoint.
For more information on queries, see the MongoDB Data API example or Mongo DB Aggregation.
dbRequest.query={collection: "books"};
Send request
Once you have filled in the request object with the necessary data, all you have to do is send it.
The result of the request will already be deserialized.
constresult=sendDBRequest(dbRequest);console.log(result);// Output: { documents: [...some book documents] }
If you want to add a type to the result of the request, pass that type as a
generic to the sendDBRequest() function.
The types for the request results of the basic endpoints provided by the MongoDB
Data API are exposed as RequestResult.
typeBook={name: string;price: number;publishDate: Date;}constdbRequest=newMongoDBRequest();dbRequest.endpoint='/findOne';dbRequest.query={collection: 'books',filter: {_id: $oid: '123'}};constresult=awaitsendDBRequest<RequestResult.ReadSingleDocument<Book>>();/** * result = { * _id: string; * name: string; * price: number; * publishDate: string; // Date object saved in MongoDB is returned as an ISO8601 formatted string * } */There are two types of errors that can occur when executing the
sendDBRequest() method.
MRHMissingParameterError
This occurs when the endpoint or query parameters are not set in the
dbRequestobject.Case when the
endpointparameter is not set:try{constdbRequest=newMongoDBRequest();// dbRequest.endpoint = '/findOne'; The endpoint parameter is not set!dbRequest.query={collection: 'books',filter: {_id: $oid: '123'}};constresult=awaitdbRequest.send();// MRHMissingParameterError!}catch(error){if(errorinstanceofMRHMissingParameterError){console.error(error.name);// Output: MRHMissingParameterErrorconsole.error(error.message);// Output: Missing required parameter: Endpoint}}
Case when the
queryparameter is not set:try{constdbRequest=newMongoDBRequest();dbRequest.endpoint="/findOne";// dbRequest.query = { collection: 'books', filter: { _id: $oid: '123'}}; The query parameter is not set!constresult=awaitdbRequest.send();}catch(error){if(errorinstanceofMRHMissingParameterError){console.error(error.name);// Output: MRHMissingParameterErrorconsole.error(error.message);// Output: Missing required parameter: Query}}
MRHRequestError
This occurs when an error is returned as a response after sending the request to the database.
try{constdbRequest=newMongoDBRequest();dbRequest.endpoint='/findOne';dbRequest.query={collection: 'books',filter: {_id: $oid: '123'}};constresult=awaitdbRequest.send();// Error!}catch(error){if(errorinstanceofMRHRequestError){console.error(error.name);// Output: MRHRequestErrorconsole.error(error.message);// Output:// Error: Database request failed <Error message from MongoDB server>// Endpoint: '/findOne'// Query: "{ 'collection': 'books' }"console.error(error.endpoint);// Output: '/find'console.error(error.query);// Output: { collection: "books" }console.error(error.mongoErrorMessage);// Output: Error message from MongoDB}}
Duplicate queries can be handled by extending the MongoDBRequest class.
classBookCollectionRequestextendsMongoDBRequest{constructor(){this.baseQuery={collection: "books",};}}constbookCollectionRequest=newBookCollectionRequest();// Insert documentbookCollectionRequest.endpoint="/InsertOne";bookCollectionRequest.query={document: {book_id: "123",name: "Book1",price: 800,publishDate: newDate("2024-08-02"),},};console.log(bookCollectionRequest.fullQuery);/** * Output: { * collection: 'books', * document: { book_id: '123', name: 'Book1', price: 800 } * } */awaitsendDBRequest(bookCollectionRequest);// delete documentbookCollectionRequest.endpoint="/deleteOne";bookCollectionRequest.query={filter: {book_id: "123"},};The endpoint property is of the BasicEndpoints type by default. You can
override this and set custom endpoints as the type of the endpoint property.
To do this, pass it as a generic type to the createMongoDBClient() function.
import{typeBasicEndpoints}from"@kokomi/mongo-request-handler";typeCustomEndpoints=BasicEndpoints|"/custom-endpoint";constdbRequest=newMongoDBRequest<CustomEndpoints>();dbRequest.endpoint="/custom-endpoint";// Type is safe.As of version 1.1.0, you can set custom headers on the MongoDBRequest object, allowing you to authenticate requests. For more information, see MongoDB Data API Authentication.
functiongetUserProfile(ctx){// Those function is fake.constaccessToken=getAccessToken(ctx);constusreId=getUserId(ctx);constdbRequest=newMongoDBRequest();dbRequest.endpoint="/findOne";dbRequest.query={collection: "users",filter: {_id: {$oid: userId}},};dbRequest.headers={Authorization: `Bearer ${accessToken}`};constresult=awaitsendDBRequest(dbRequest);constuser=result.document;returnuser;}Q: What is the base URL?
A: The base URL is the URL provided by MongoDB Data API for your database.
Q: How do I handle authentication?
A: The API key provided in the database configuration is used for authentication.
Q: Can I use this with any MongoDB database?
A: Yes, as long as the MongoDB database is accessible via the Data API.
MIT