{"id":24618073,"url":"https://github.com/winkgroup/db-mongo","last_synced_at":"2025-06-26T07:31:53.398Z","repository":{"id":57747612,"uuid":"523041649","full_name":"WINKgroup/db-mongo","owner":"WINKgroup","description":"MongoDB connection class","archived":false,"fork":false,"pushed_at":"2025-06-21T13:17:19.000Z","size":167,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-06-21T13:17:43.339Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WINKgroup.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":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-08-09T17:12:37.000Z","updated_at":"2025-06-21T13:17:21.000Z","dependencies_parsed_at":"2024-03-19T19:43:38.867Z","dependency_job_id":"f44eb5fb-fe98-499f-af40-b0e75d8fd13b","html_url":"https://github.com/WINKgroup/db-mongo","commit_stats":{"total_commits":37,"total_committers":1,"mean_commits":37.0,"dds":0.0,"last_synced_commit":"c1a0c898155cbd56478d9d814036ec8dbe51ed39"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"purl":"pkg:github/WINKgroup/db-mongo","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WINKgroup%2Fdb-mongo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WINKgroup%2Fdb-mongo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WINKgroup%2Fdb-mongo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WINKgroup%2Fdb-mongo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WINKgroup","download_url":"https://codeload.github.com/WINKgroup/db-mongo/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WINKgroup%2Fdb-mongo/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262022350,"owners_count":23246303,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2025-01-24T23:49:42.886Z","updated_at":"2025-06-26T07:31:53.301Z","avatar_url":"https://github.com/WINKgroup.png","language":"TypeScript","readme":"# db-mongo\nHelper functions for mongodb and mongoose.\nHere some features:\n- realtime queries (RealtimeQuery class)\n- persistent variables as in key-value paradigm (DbVar class)\n\n## Prerequisites\nEnsure you have a MongoDB database set up and the necessary MongoDB drivers installed in your project. This class is intended to be used in a TypeScript environment.\n\n## Installation\n```sh\nnpm install @winkgroup/db-mongo\n```\n\nor\n\n```sh\nyarn add @winkgroup/db-mongo\n```\n\n## RealtimeQuery \nRealtimeQuery class is designed for managing real-time queries with MongoDB. This class uses MongoDB's Change Streams feature, which allows applications to access real-time data changes without the complexity and risk of tailing the oplog. Change streams are available for replica sets and sharded clusters.\n\nChange Streams, and consequently the *watch()* function, require a replica set or sharded cluster configuration. This is because they rely on the oplog (operations log) for tracking changes, and a standalone MongoDB server (single-node instance) does not maintain an oplog by default.\n\nIt's worth noting that you can configure a single-node instance of MongoDB to run as a replica set, which enables the oplog and allows the use of change streams. This setup is sometimes used for development purposes. However, in a production environment, a replica set typically consists of multiple nodes for redundancy and failover capabilities.\n\n### Usage\nHere an usage example:\n```js\nimport { MongoClient } from 'mongodb';\nimport { RealtimeQuery } from '@winkgroup/db-mongo';\n\nasync function main() {\n    // Connection URL and database/collection names\n    const url = 'your-mongodb-connection-string';\n    const dbName = 'your-database-name';\n    const collectionName = 'your-collection-name';\n\n    // Create a new MongoClient\n    const client = new MongoClient(url);\n\n    try {\n        // Connect the client to the server\n        await client.connect();\n        console.log(\"Connected successfully to server\");\n\n        // Get the database and collection\n        const db = client.db(dbName);\n        const collection = db.collection(collectionName);\n\n        // Instantiate RealtimeQuery\n        const realtimeQuery = new RealtimeQuery({\n            db: db,\n            collectionName: collectionName,\n        });\n\n        // Subscribe to real-time updates\n        realtimeQuery.subscribe(\n            {\n                queryObj: {}, // Empty query object means 'all documents'\n                limit: 50,\n                skip: 0,\n            },\n            (list) =\u003e {\n                console.info('Received new data:', list);\n            }\n        );\n\n        // Start listening to changes\n        realtimeQuery.start();\n    }\n}\n\nmain().catch(console.error);\n```\n\n### Methods\n- **subscribe(queryParams: QueryParams, callback: QueryCallback\u003cDoc\u003e)**: Subscribe to changes in the database. Triggers the callback when the query result changes. It returns a subscriberId.\n- **unsubscribe(subscriberId: string)**: Unsubscribe from changes. Stops receiving updates for the specified subscription.\n\nwhere:\n```js\ninterface QueryParams {\n    queryObj: object;\n    limit: number;\n    skip: number;\n    sort?: object;\n}\n\ntype QueryCallback\u003cDoc\u003e = (\n    list: Doc[],\n    changeDoc: ChangeStreamDocument,\n    changeList: ChangeQueryDocumentList\u003cDoc\u003e\n) =\u003e void;\n```\n\nand **\"Doc\"** represents a generic type parameter. It's a placeholder for the actual type of the documents that you'll be working with in your MongoDB collection. \n\n### Interactive Integration Test\nUnder *playground* folder some extra code is provided to make some interctive integration tests.\nThis is a command line interface test realtime queries\nHere the steps to run this test:\n1. copy *playground/config.template.json* to *playground/config.json*\n1. edit *playground/config.json* setting the credetials of a real mega account\n2. run ```npm run realtime``` or ```yarn realtime```\n\n## DbVar Class\nThe DbVar class provides an abstraction over a MongoDB collection, allowing you to manage the variables stored in the collection easily. The main methods are:\n- **get(name: string)**: Retrieves the value of a variable by its name.\n- **set(name: string, value: any)**: Sets or updates the value of a variable.\n- **unset(name: string)**: Removes a variable from the collection.\n\nWhen creating a new DbVar object, you can optionally specify the name of the collection you want to use. If not provided, the default **\"vars\"** collection name is used.\n\nTo use the DbVar class, you need an instance of MongoDB's Db class. Here's how you can utilize the DbVar methods:\n```js\nimport DbVar from '@winkgroup/db-mongo';\nimport { MongoClient } from 'mongodb';\n\n// Connect to your MongoDB database\nconst client = new MongoClient('your-mongodb-connection-string');\nawait client.connect();\nconst db = client.db('your-database-name');\n\n// Create an instance of DbVar\nconst customCollectionName = 'myCustomCollection'; // optional\nconst dbVar = new DbVar(db, customCollectionName);\n\n// Set a variable\nawait dbVar.set('myVar', 'myValue');\n\n// Get a variable\nconst value = await dbVar.get('myVar');\nconsole.log(value);  // Output: 'myValue'\n\n// Unset a variable\nawait dbVar.unset('myVar');\n```\n\n## License\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Maintainers\n* [fairsayan](https://github.com/fairsayan)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinkgroup%2Fdb-mongo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwinkgroup%2Fdb-mongo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinkgroup%2Fdb-mongo/lists"}