{"id":16323,"library":"cry-db","title":"cry-db MongoDB Wrapper","description":"cry-db is a TypeScript-first MongoDB wrapper library, currently stable at version 2.4.31. Its versioning suggests active development, though a specific release cadence isn't published. It offers a high-level, opinionated API for common database operations, abstracting away direct MongoDB driver interactions. Key differentiators include built-in support for document revisions, soft-delete functionality, archiving, blocking, and auditing, which simplify complex data lifecycle management. The library also provides real-time publish events, enabling reactive applications. It offers two main interfaces: `Mongo` for flexible multi-collection operations and `Repo<T>` for type-safe, single-collection convenience. Connection details are automatically managed via `MONGO_URL` and `MONGO_DB` environment variables, streamlining setup. A central feature is its unique record lifecycle, where soft-deleted and archived records are filtered from standard queries by default, requiring explicit options to retrieve them.","status":"active","version":"2.4.31","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","typescript"],"install":[{"cmd":"npm install cry-db","lang":"bash","label":"npm"},{"cmd":"yarn add cry-db","lang":"bash","label":"yarn"},{"cmd":"pnpm add cry-db","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"`Repo` is a named export, commonly used as a type-safe convenience class for single-collection operations.","wrong":"const Repo = require('cry-db').Repo;","symbol":"Repo","correct":"import { Repo } from 'cry-db';"},{"note":"`Mongo` is a named export, providing lower-level, multi-collection database operations.","wrong":"const Mongo = require('cry-db').Mongo;","symbol":"Mongo","correct":"import { Mongo } from 'cry-db';"},{"note":"`cry-db` re-exports the `ObjectId` class from the underlying MongoDB driver for working with document IDs.","wrong":"import { Types } from 'cry-db'; // For ObjectId","symbol":"ObjectId","correct":"import { ObjectId } from 'cry-db';"}],"quickstart":{"code":"import { Repo, Mongo, ObjectId } from 'cry-db';\n\n// Ensure MongoDB is running and accessible via MONGO_URL and MONGO_DB environment variables.\n// Example: process.env.MONGO_URL = 'mongodb://127.0.0.1:27017';\n// Example: process.env.MONGO_DB = 'mytestdb';\n\nasync function runExample() {\n    // Repo — single-collection convenience class with type safety\n    const users = new Repo<{ _id?: ObjectId, name: string, age: number, active?: boolean }>('users', process.env.MONGO_DB || 'testdb');\n\n    // Mongo — multi-collection class for more granular control\n    const mongo = new Mongo(process.env.MONGO_DB || 'testdb');\n\n    console.log('--- Repo operations (users collection) ---');\n\n    // Insert a new user\n    let alice = await users.insert({ name: 'Alice', age: 30 });\n    console.log('Inserted Alice:', alice);\n\n    // Find Alice by name\n    let foundAlice = await users.findOne({ name: 'Alice' });\n    console.log('Found Alice:', foundAlice);\n\n    // Update Alice's age\n    await users.updateOne({ name: 'Alice' }, { $set: { age: 31 } });\n    let updatedAlice = await users.findOne({ name: 'Alice' });\n    console.log('Updated Alice:', updatedAlice);\n\n    // Demonstrate soft-delete (opt-in) and retrieval\n    await users.useSoftDelete(true); // Enable soft-delete for this Repo instance\n    if (updatedAlice?._id) {\n        await users.deleteOne({ _id: updatedAlice._id });\n        console.log('Soft-deleted Alice. Trying to find (should be null):', await users.findOne({ _id: updatedAlice._id }));\n        console.log('Finding deleted Alice (with returnDeleted):', await users.findOne({ _id: updatedAlice._id }, { returnDeleted: true }));\n\n        // Cleanup (hard delete to permanently remove)\n        await users.hardDeleteOne(updatedAlice._id);\n    }\n    console.log('Count after cleanup:', await users.count({}));\n\n    console.log('\\n--- Mongo operations (products collection) ---');\n\n    // Mongo can operate on any collection without creating a dedicated Repo instance\n    const productsCollection = 'products';\n    let product1 = await mongo.insert(productsCollection, { name: 'Laptop', price: 1200 });\n    console.log('Inserted Laptop:', product1);\n\n    let foundProduct = await mongo.findOne(productsCollection, { name: 'Laptop' });\n    console.log('Found Laptop:', foundProduct);\n\n    // Clean up\n    if (product1?._id) {\n        await mongo.hardDelete(productsCollection, { _id: product1._id });\n    }\n    console.log('Hard-deleted Laptop.');\n}\n\nrunExample().catch(console.error);\n","lang":"typescript","description":"This quickstart demonstrates basic CRUD operations using both the `Repo` and `Mongo` classes, including an example of soft-delete and how to retrieve filtered records, and highlights the reliance on environment variables for MongoDB connection."},"warnings":[{"fix":"To retrieve soft-deleted records, pass `{ returnDeleted: true }` in `QueryOpts`. For archived records, use `{ returnArchived: true }`. To bypass all filters, use `findAll`.","message":"When soft-delete (`_deleted`) or archiving (`_archived`) features are enabled, most query methods automatically filter out records marked as deleted or archived by default. This can lead to seemingly missing documents.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"To permanently remove a document from the database, use `hardDeleteOne()` or `hardDelete()`.","message":"The `deleteOne()` and `delete()` methods perform a *soft-delete* (setting the `_deleted` flag) if soft-delete is enabled for the `Repo` instance. They do not physically remove the document.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Ensure `process.env.MONGO_URL` and `process.env.MONGO_DB` are correctly configured in your application environment or explicitly pass the database name to the `Repo` or `Mongo` constructor.","message":"Connection to MongoDB relies on `MONGO_URL` and `MONGO_DB` environment variables by default. If these are not set, the library will attempt to connect to `mongodb://127.0.0.1:27017` and use the default database name 'test'.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Be aware of these automatic field additions and updates, especially when performing partial updates or expecting specific document shapes. Integrate `_rev` and `_ts` into your document interfaces (`T`) for type safety if using `Repo<T>`.","message":"When revisions are enabled (`useRevisions(true)`), every write operation (insert, update) automatically increments the `_rev` field and updates the `_ts` (timestamp) field on documents.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure your MongoDB instance is running. Verify that `process.env.MONGO_URL` (or the explicit database name in the constructor) is correctly pointing to your MongoDB server address and port.","cause":"The MongoDB server is not running or is not accessible at the configured `MONGO_URL` (often the default `mongodb://127.0.0.1:27017`).","error":"MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017"},{"fix":"When calling query methods like `find` or `findOne`, pass `{ returnDeleted: true }` and/or `{ returnArchived: true }` in the options object to include these records in the results. Alternatively, use `findAll` which bypasses these filters.","cause":"Documents might be marked as soft-deleted (`_deleted`) or archived (`_archived`), and standard queries automatically filter these out by default.","error":"Query returns no documents, but I know they exist."}],"ecosystem":"npm"}