{"id":21373189,"url":"https://github.com/nasriyasoftware/mongodb","last_synced_at":"2026-02-15T12:37:27.203Z","repository":{"id":239784516,"uuid":"789678651","full_name":"nasriyasoftware/MongoDB","owner":"nasriyasoftware","description":"A MongoDB client with schemas, data-hooks, permissions, and more.","archived":false,"fork":false,"pushed_at":"2025-04-08T19:32:59.000Z","size":325,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-21T16:49:43.174Z","etag":null,"topics":["data-hooks","database","database-hooks","database-management","database-schema","mongodb","schema"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@nasriya/mongodb","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nasriyasoftware.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-04-21T08:44:01.000Z","updated_at":"2025-04-08T19:30:48.000Z","dependencies_parsed_at":"2025-04-14T12:08:09.137Z","dependency_job_id":"d23b43c7-10a9-4dca-87b3-001ddda04b12","html_url":"https://github.com/nasriyasoftware/MongoDB","commit_stats":null,"previous_names":["nasriyasoftware/mongodb"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/nasriyasoftware/MongoDB","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nasriyasoftware%2FMongoDB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nasriyasoftware%2FMongoDB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nasriyasoftware%2FMongoDB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nasriyasoftware%2FMongoDB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nasriyasoftware","download_url":"https://codeload.github.com/nasriyasoftware/MongoDB/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nasriyasoftware%2FMongoDB/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29478355,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-15T11:35:25.641Z","status":"ssl_error","status_checked_at":"2026-02-15T11:34:57.128Z","response_time":118,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-hooks","database","database-hooks","database-management","database-schema","mongodb","schema"],"created_at":"2024-11-22T08:26:13.900Z","updated_at":"2026-02-15T12:37:27.189Z","avatar_url":"https://github.com/nasriyasoftware.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![N|Solid](https://static.wixstatic.com/media/72ffe6_da8d2142d49c42b29c96ba80c8a91a6c~mv2.png)](https://nasriya.net)\n# MongoDB.\n[![Static Badge](https://img.shields.io/badge/license-Free_(Restricted)-blue)](https://github.com/nasriyasoftware/MongoDB?tab=License-1-ov-file) ![Repository Size](https://img.shields.io/github/repo-size/nasriyasoftware/MongoDB.svg) ![Last Commit](https://img.shields.io/github/last-commit/nasriyasoftware/MongoDB.svg) [![Status](https://img.shields.io/badge/Status-Stable-green.svg)](link-to-your-status-page)\n##### Visit us at [www.nasriya.net](https://nasriya.net).\n\nA MongoDB client with [schemas](#collection-schemas), [data-hooks](#collection-hooks), [permissions](#collection-permissions), and more.\n\nMade with ❤️ in **Palestine** 🇵🇸\n\n\u003e [!IMPORTANT]\n\u003e 🌟 **Support Our Open-Source Development!** 🌟\n\u003e We need your support to keep our projects going! If you find our \u003e work valuable, please consider contributing. Your support helps us \u003e continue to develop and maintain these tools.\n\u003e \n\u003e **[Click here to support us!](https://fund.nasriya.net/)**\n\u003e \n\u003e Every contribution, big or small, makes a difference. Thank you for \u003e your generosity and support!\n\u003e \n___\n## 📚 Full Documentation\n- [Getting Started](#getting-started).\n  - Installation.\n  - Importing.\n  - [Preparing the Environment](#preparing-the-environment).\n    - [Defining Databases and Collections](#defining-databases-and-collections).\n    - [Creating \u0026 Using Clients](#creating--using-clients).\n  - [Advanced Collection Typing (TypeScript)](#advanced-collection-typing-typescript).\n- [CRUD Operations](#crud-operations).\n  - [➕ Creating Data](#-creating-data).\n  - [🔍 Reading Data](#-reading-data).\n    - [Getting an item](#getting-an-item).\n    - [Building \u0026 Executing queries](#querying-data)\n  - [📝 Updating Data](#-updating-data).\n  - [🗑️ Deleting Data](#️-deleting-data).\n- [Upcoming Features](#upcoming-features)\n- [Error Handling]().\n___\n## Getting Started\n\n### Installation\n```shell\nnpm i @nasriya/mongodb\n```\n\n### Importing\nImport in **ESM** modules:\n```js\nimport mongodb from '@nasriya/mongodb';\n```\n\nImport in **CommonJS (CJS)**\n```js\nconst mongodb = require('@nasriya/mongodb').default;\n```\n\n### Preparing the Environment\n\n#### Defining Databases and Collections\nYou can define databases and collections using the `defineDatabase` method. Here’s an example of how to define a simple database setup:\n\n```js\nmongodb.defineDatabase({\n    name: 'Auth',\n    collections: [{ name: 'Passwords' }, { name: 'Sessions' }]\n});\n\nmongodb.defineDatabase({\n    name: 'Blog',\n    collections: [{ name: 'Posts' }, { name: 'Comments' }]\n})\n```\n##### More Details\nFor advanced features like defining schemas, permissions, and more, refer to the [Defining Databases](\u003c./docs/Preparing the Environment/defining-databases.md\u003e) page.\n\n#### Defining Connections\nOur **MongoDB** driver makes it easy to manage cluster connections by defining it once, and use it simply by referencing its name when creating a client.\n\nConnections are defined using the `defineConnection` method.\n\n```ts\ndefineConnection(name: string, connectionString: string): string\n```\n\nExample:\n```js\nconst localServer = mongodb.defineConnection('localServer', 'mongodb://localhost:27017');\n\nconsole.log(localServer); // ⇨ 'localServer'\n```\nYou can see that the `defineConnection()` method returns the connection name, so you can use it directly when [creating clients](./docs/creating-clients.md), or you can use the name instead.\n\n#### Creating \u0026 Using Clients\nOur MongoDB driver allows you to create flexible clients for different clusters or users, providing secure and efficient access to your databases.\n\n##### Basic Client Creation\nTo create a client, you need to specify the connection name using the `createClient` method. The `connection` property is required.\n```js\nconst client = mongodb.createClient({ name: 'LocalServer' });\n```\n\n##### Authorization Levels\nYou can set the authorization level for the client:\n- `System`: Bypasses all collection-level permissions.\n- `User`: Enforces collection-level permissions based on the user’s role and ID.\n\n```js\nconst systemClient = mongodb.createClient({\n    name: 'LocalServer', \n    authorization: 'System'\n});\n\nconst userClient = mongodb.createClient({\n    name: 'LocalServer', \n    authorization: 'User',\n    user: { id: 'userId', role: 'Member', loggedIn: true }\n});\n\nconst userClient2 = mongodb.createClient({\n    name: 'LocalServer', \n    authorization: 'User',\n    user: { id: 'userId', role: 'Member', loggedIn: true },\n    defaultDatabase: 'Members'\n});\n```\nIf you didn't specify a default database when creating the client, or if you wish to switch between databases during runtime, you can easily set the database to use like this:\n```js\n// Switch or specify a database after creating the client\nclient.db('Auth');\n```\nThis method allows you to dynamically change the database context for your operations. You can now perform actions like querying, inserting, or updating documents within the specified Auth database, without having to recreate the client.\n\n**Note:** If you haven't set a default database during client initialization, calling client.db() is required before making database operations.\n\nFor more details on creating clients, see [Creating Clients](./docs/creating-clients.md).\n\n### Advanced Collection Typing (TypeScript)\nTo enable full type-safety and autocomplete when working with your collections, you can define your own interfaces by extending the base `CollectionItem` type.\n\nAll items created **and** returned by this adapter are based on the `CollectionItem` interface:\n\n```ts\n/** Represents an item in a collection. */\ninterface CollectionItem {\n    /** The ID of the item. */\n    _id: string;\n    /** The date this item was created at. */\n    _createdDate: Date;\n    /** The date this item was last updated at. */\n    _updatedDate: Date;\n    /** The ID of the owner. */\n    _owner: string;\n    /** Additional properties */\n    [key: string]: any;\n}\n```\n\nYou can create your own collection interfaces by extending this base interface:\n```ts\nimport { CollectionItem } from '@nasriya/mongodb';\n\ninterface UserItem extends CollectionItem {\n    name: string;\n    email: string;\n}\n```\n\nThen use it with your collection like this:\n```ts\nconst user: UserItem = await client.getItem('Members', 'userId');\n```\nThis helps prevent mistakes, enables richer development tooling, and makes your data layer more robust.\n___\n### CRUD Operations\n##### NasriyaDataOptions\nBefore we dive into each of the CRUD operations, it's important to understand the `NasriyaDataOptions` interface, which can be used across various operations to customize their behavior.\n\n```ts\n/** Options for data operations. */\nexport interface NasriyaDataOptions {\n    /** Prevents permission checks from running for the operation. Defaults to `false`. */\n    suppressAuth?: boolean;\n    /** Prevents hooks from running for the operation. Defaults to `false`. */\n    suppressHooks?: boolean;\n}\n```\nProperties:\n- `suppressAuth`:\n  - If set to `true`, this option will skip any authentication or authorization checks that would normally be run for the operation. This is useful when you want to perform an operation without enforcing the usual security measures.\n  - Defaults to `false`.\n- `suppressHooks`:\n  - If set to `true`, this option will prevent any hooks (e.g., pre-insert or post-insert hooks) from running during the operation. This is useful when you want to bypass custom logic that might be applied during these operations.\n  - Defaults to `false`.\n\nThese options can be passed to any CRUD operation where you want to modify the default behavior, such as `insert`, `bulkInsert`, `find`, etc.\n\n#### ➕ Creating Data\nTo add new items to a collection, you can use the `insert` or `bulkInsert` methods provided by the client. These methods allow you to insert a single item or multiple items into a collection, respectively.\n\n###### **Insert a Single Item**\n```ts\ninsert(collectionName: string, item: Item, options?: NasriyaDataOptions): Promise\u003cCollectionItem\u003e;\n```\nThe `insert` method is used to insert a single item into a collection. Here's how you can use it:\n\nExample:\n```js\nclient.insert('Members', { name: 'John Doe', email: 'john.doe@example.com' });\n```\n\n**Parameters:**\n- `collectionName`: The name of the collection where the item will be inserted (e.g.,   `Members`).\n- `item`: The object you want to insert. This should conform to the collection's item   interface(e.g., `CollectionItem`).\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\n**Returns:** A promise that resolves to the inserted `CollectionItem`, which includes the unique`_id` of the item and other metadata (like `_createdDate` and  `_updatedDate`).\n\u003cbr\u003e\n\n###### **Bulk Insert Multiple Items**\n```ts\nbulkInsert(collectionName: string, items: Item[], options: NasriyaDataOptions = { suppressAuth: false, suppressHooks: false }): Promise\u003cBulkInsertResult\u003e\n```\nThe `bulkInsert` method allows you to insert an array of items into a collection at once, making it more efficient when dealing with large datasets.\n\nExample:\n```js\nclient.bulkInsert('Members', [\n    { name: 'Charlie', email: 'charlie@example.com' },\n    { name: 'Eve', email: 'eve@example.com' }\n]);\n```\n\n**Parameters:**\n- `collectionName`: The name of the collection where the items will be inserted (e.g.,   `Members`).\n- `items`: An array of objects to insert. Each object should conform to the collection's it\ninterface.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\n**Returns:** A promise that resolves to the result of the bulk insert operation (`BulkInsertResult`), which contains details like the number of inserted items.\n\n```ts\n/** Result of a bulk insert operation. */\nexport interface BulkInsertResult {\n    /** The inserted items. */\n    items: CollectionItem[];\n    /** Statistics about the operation. */\n    stats: {\n        /** The number of inserted items. */\n        inserted: number;\n        /** The number of skipped items. */\n        skipped: number;\n        /** The IDs of the inserted items. */\n        insertedIds: string[];\n        /** The IDs of the skipped items. */\n        skippedIds: string[];\n    };\n}\n``` \n\nExample:\n```js\nconst result = await client.bulkInsert('Members', [\n    { name: 'David', email: 'david@example.com' },\n    { name: 'Zara', email: 'zara@example.com' }\n]);\n\nconsole.log('Bulk Insert Result:', result.stats);\nconsole.log('Inserted Items:', result.items);\nconsole.log('Inserted IDs:', result.stats.insertedIds);\nconsole.log('Skipped IDs:', result.stats.skippedIds);\n```\n\n#### 🔍 Reading Data\nYou can retrieve data from your collections using the following methods: `getItem`, `find`, and `count`. Each method allows you to specify optional operation options using the NasriyaDataOptions.\n\n##### Getting an item\n```ts\ngetItem(collectionName: string, itemId: string, options?: NasriyaDataOptions): Promise\u003cCollectionItem | null\u003e;\n```\nUse getItem to retrieve a single item from a collection by its ID.\n\n**Parameters:**\n- `collectionName`: The collection ID from which to retrieve the item.\n- `itemId`: The ID of the item to retrieve.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\n**Returns** `Promise\u003cCollectionItem | null\u003e` containing the item if it exists, or `null` if no item matches the provided ID.\n\nExample:\n```js\nconst member = await client.getItem('Members', 'd8a9e87b-2a3f-4f0c-b6a5-9a5364a1c2a4');\n\nif (member) {\n    console.log(member.name);\n} else {\n    console.log('User not found');\n}\n```\n\n##### Querying Data\n```ts\nquery(collectionName: string): DataQuery;\n```\nTo perform advanced data queries on your collections, use the `query()` method. This returns a `DataQuery` instance, which provides powerful utilities like filtering, pagination, and data retrieval.\n\n**Basic Example**\n```js\nconst query = client.query('Members');\n```\n\nFor advanced usage with filters and pagination, [see the full guide on building a query →](./docs/query-building.md)\n\n\n##### 🚀 Executing the Query\nOnce you've built a query using `client.query()`, there are two primary ways to execute it:\n1. Fetching the actual results – using `.find()`\n   ```js\n   const result = await client.query('Members')\n    .filter(client.filter().eq('role', 'admin'))\n    .limit(10)\n    .skip(0)\n    .find();\n   ```\n   **Returns** a promise that resolves to a `DataQuery` instance.\n\n   **Parameters:**\n   - `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\n  \u003cbr\u003e\n2. Getting the number of matching items – using `.count()`\n\n   ```js\n   const total = await client.query('Members')\n    .filter(client.filter().eq('role', 'admin'))\n    .count();\n   ```\n\n   **Returns** a promise that resolves to a number.\n\n   **Parameters:**\n   - `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\nWants to learn how to build powerful filters?\n🔗 [See the Filter Builder →](./docs/data-filter.md)\n\n#### 📝 Updating Data\nYou can update records in your database using four different methods:\n\n- `update`: Update a single item that must already exist.\n- `bulkUpdate`: Update multiple items that must already exist.\n- `save`: Create or update a single item — more flexible.\n- `bulkSave`: Create or update multiple items — more flexible.\n\n##### 🧩 Understanding the Difference\n| Method       | Requires `_id` | Fails if item doesn't exist | Can create new item |\n| ------------ | -------------- | --------------------------- | ------------------- |\n| `update`     | ✅ Yes          | ✅ Yes                       | ❌ No                |\n| `bulkUpdate` | ✅ Yes          | ✅ Yes                       | ❌ No                |\n| `save`       | ❌ Optional     | ❌ No                        | ✅ Yes               |\n| `bulkSave`   | ❌ Optional     | ❌ No                        | ✅ Yes               |\n\n- Use `update` / `bulkUpdate` when you're sure the items already exist.\n- Use `save` / `bulkSave` when you want to either insert or update items as needed.\n\n##### Updating a Single Item with `update()`\n```js\nawait client.update('Members', {\n    _id: 'abc123',\n    name: 'Ahmad Nasriya'\n});\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `item`: An item that must contain a valid `_id`.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\u003cbr\u003e\n\n##### Updating Multiple Items with `bulkUpdate()`\n```js\nawait client.bulkUpdate('Members', [\n    { _id: 'id1', name: 'John' },\n    { _id: 'id2', name: 'Jane' }\n]);\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `items`: An array of items that must each contain a valid `_id`.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\u003cbr\u003e\n\n##### Saving a Single Item with `save()`\n```js\nawait client.save('Members', {\n    name: 'Ahmad Nasriya',\n    email: 'me@nasriya.com'\n});\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `item`: An item that may or may not include an `_id`.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\u003cbr\u003e\n\n##### Saving Multiple Items with `bulkSave()`\n```js\nawait client.bulkSave('Members', [\n    { name: 'Ali' },                            // Insert\n    { _id: 'id3', name: 'Updated Member' }      // Update\n]);\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `items`: Array of items to save — new ones will be inserted, existing ones updated.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\u003cbr\u003e\n\n#### 🗑️ Deleting Data\nTo delete items from your database, you can use:\n- `remove`: Delete a single item by its ID.\n- `bulkRemove`: Delete multiple items using their IDs.\n\n##### Deleting a Single Item with `remove()`\n```js\nawait client.remove('Members', 'abc123');\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `itemId`: The `_id` of the item to remove.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\u003cbr\u003e\n\n##### Deleting Multiple Items with `bulkRemove()`\n```js\nawait client.bulkRemove('Members', ['id1', 'id2', 'id3']);\n```\n**Parameters:**\n- `collectionName`: The collection ID to use.\n- `itemIds`: An array of item `_id`s to remove.\n- `options`: Optional [NasriyaDataOptions](#nasriyadataoptions) options for the operation.\n\n___\n## 🚀 Upcoming Features\n\n- [Geographically Distributed Databases \u0026 Failover](./docs/Upcoming%20Features/distributed-database-architecture.md).\n- [Built-in Caching \u0026 Cache Broker Integration](./docs/Upcoming%20Features/caching.md).\n\n___\n## ⚠️ Error Handling (Coming Soon)\nError handling is an important part of any robust system, and we are working on implementing a comprehensive error handling mechanism. In the near future, errors will be communicated through specific error codes and detailed messages, making it easier for developers to understand and address issues in their applications.\n\nStay tuned for updates on how errors will be managed and reported in future versions!\n___\n## License\nPlease read the license from [here](https://github.com/nasriyasoftware/MongoDB?tab=License-1-ov-file).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnasriyasoftware%2Fmongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnasriyasoftware%2Fmongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnasriyasoftware%2Fmongodb/lists"}