{"id":14956842,"url":"https://github.com/mib-kamel/mongo-strict","last_synced_at":"2025-08-17T13:39:43.320Z","repository":{"id":58520038,"uuid":"531997715","full_name":"mib-kamel/mongo-strict","owner":"mib-kamel","description":"Mongo Strict is a TypeScript based smart MongoDB ORM, It makes the usage of MongoDB safer, easier and faster with a better performance...","archived":false,"fork":false,"pushed_at":"2023-07-04T04:58:10.000Z","size":1604,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-13T18:48:50.298Z","etag":null,"topics":["backend","decorat","javascript","mongo","mongo-db","mongo-orm","mongodb","mongodb-orm","nestjs","nodejs","orm","relational-databases","strict","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/mongo-strict","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/mib-kamel.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}},"created_at":"2022-09-02T16:19:01.000Z","updated_at":"2024-07-07T21:15:06.000Z","dependencies_parsed_at":"2025-02-09T12:41:41.194Z","dependency_job_id":null,"html_url":"https://github.com/mib-kamel/mongo-strict","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/mib-kamel/mongo-strict","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mib-kamel%2Fmongo-strict","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mib-kamel%2Fmongo-strict/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mib-kamel%2Fmongo-strict/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mib-kamel%2Fmongo-strict/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mib-kamel","download_url":"https://codeload.github.com/mib-kamel/mongo-strict/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mib-kamel%2Fmongo-strict/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270791277,"owners_count":24645782,"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","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["backend","decorat","javascript","mongo","mongo-db","mongo-orm","mongodb","mongodb-orm","nestjs","nodejs","orm","relational-databases","strict","typescript"],"created_at":"2024-09-24T13:13:37.124Z","updated_at":"2025-08-17T13:39:43.287Z","avatar_url":"https://github.com/mib-kamel.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# mongo-strict\n\n![Lines](https://img.shields.io/badge/lines-97.02%25-brightgreen.svg?style=flat)\n![Statements](https://img.shields.io/badge/statements-96.94%25-brightgreen.svg?style=flat)\n![Functions](https://img.shields.io/badge/functions-98.49%25-brightgreen.svg?style=flat)\n![Branches](https://img.shields.io/badge/branches-87.5%25-yellow.svg?style=flat)\n\n**mongo-strict is compatible with mongo \u003e= 5**\n\nMongo Strict is a TypeScript-based smart MongoDB ORM, It makes the usage of MongoDB safer, easier and faster with better performance...\n\nmongo-strict gives you the safety of the SQL DBs with keeping the flexibility and the ease of use of MongoDB.\n\n## mongo-strict Allows you to\n\n- Define the **entity data types** and ensure the data validity (Using class-validator in the background).\n- Define the **relations between the data**.\n- Add a **default value** for any field.\n- Mark any field as **required**.\n- Get the **related data using the reference keys** whithout using any complicated lookups.\n- Imporove the **App performance** by using the best practices in the background.\n- Imporove the **code quality**.\n- **Cache** any query for a better performance.\n\n## Table of Contents\n\n- [mongo-strict](#mongo-strict)\n  - [mongo-strict Allows you to](#mongo-strict-allows-you-to)\n  - [Table of Contents](#table-of-contents)\n  - [Instalation](#instalation)\n  - [Usage](#usage)\n  - [Create Connection](#create-connection)\n  - [Add Repository](#add-repository)\n    - [Repository Options](#repository-options)\n  - [Entity Class](#entity-class)\n    - [Entity Validation](#entity-validation)\n      - [class-validator](#class-validator)\n      - [IsRequired](#isrequired)\n      - [IsUnique](#isunique)\n      - [Default](#default)\n      - [RefersTo](#refersto)\n        - [RefersTo Options](#refersto-options)\n    - [Referers](#referers)\n      - [Referer Options](#referer-options)\n  - [Initialize the DB Map](#initialize-the-db-map)\n  - [Operations](#operations)\n    - [find(findOptions: FindOptions)](#findfindoptions-findoptions)\n      - [FindOptions](#findoptions)\n      - [find example](#find-example)\n    - [findAndCount(findOptions: FindOptions)](#findandcountfindoptions-findoptions)\n    - [findOne(findOptions: FindOptions)](#findonefindoptions-findoptions)\n    - [count(findOptions: FindOptions)](#countfindoptions-findoptions)\n    - [findOneById(id: string, select)](#findonebyidid-string-select)\n    - [Query Caching](#query-caching)\n    - [Query Builder](#query-builder)\n    - [Find reference Entities](#find-reference-entities)\n    - [Populate](#populate)\n    - [insertOne](#insertone)\n      - [validateInsertData](#validateinsertdata)\n    - [Update(filter: object | id: string)](#updatefilter-object--id-string)\n      - [1- setOne(data)](#1--setonedata)\n      - [2- setMany(data)](#2--setmanydata)\n      - [3- replaceOne(completeEntityData)](#3--replaceonecompleteentitydata)\n    - [Errors Handling](#errors-handling)\n      - [Invalid data error](#invalid-data-error)\n      - [Existing Unique Keys](#existing-unique-keys)\n      - [Not Found Reference Keys](#not-found-reference-keys)\n    - [deleteOne(filter: any | id: string)](#deleteonefilter-any--id-string)\n    - [deleteMany(filter: any | ids: string\\[\\])](#deletemanyfilter-any--ids-string)\n    - [getCollection()](#getcollection)\n    - [getDB()](#getdb)\n    - [getConnectionManager()](#getconnectionmanager)\n  - [Roadmap](#roadmap)\n\n## Instalation\n\n```JavaScript\nnpm install mongo-strict --save\n```\n\n## Usage\n\nExample: Suppose we have CVs management system =\u003e Every user can create multiple CVs and every CV has multiple sections.\n\nCreate your Database connection with the connection URL\n\n```JavaScript\nimport { createConnection } from 'mongo-strict';\n\nawait createConnection({\n    uri: `mongodb://127.0.0.1:27017/fancy-cvs`\n});\n```\n\nDefine your DB Repositories:\n\n```JavaScript\nimport { addRepository, Entity, IsRequired, IsUnique, ORMOperations, Allow, IsEmail, MinLength, IsString, IsArray, RefersTo } from 'mongo-strict';\n\n@Entity({ name: 'user' })\nclass UserEntity {\n    @Allow()\n    @IsEmail(undefined, { message: \"The email should be valid :(\" })\n    @IsUnique({ isIgnoreCase: true })\n    email: string;\n\n    @Allow()\n    @IsRequired()\n    @MinLength(3)\n    name: string;\n\n    @Allow()\n    @IsString()\n    country: string;\n\n    @Allow()\n    @IsArray()\n    @RefersTo({\n        collection: 'cv',\n        key: 'id',\n        isArray: true\n    })\n    cvs: any[];\n}\n\nexport class UserRepository extends ORMOperations {\n    constructor() {\n        const ORM = addRepository(UserEntity, { debug: false });\n        super(ORM);\n    }\n}\n\n```\n\n```JavaScript\nimport { addRepository, Entity, IsRequired, ORMOperations, RefersTo, IsString, Allow, IsArray } from 'mongo-strict';\n\n@Entity({ name: 'cv' })\nclass CVEntity {\n    @Allow()\n    @IsRequired()\n    @IsString()\n    cvName: string;\n\n    @Allow()\n    @IsRequired()\n    @IsString()\n    currentPosition: string;\n\n    @Allow()\n    @IsArray()\n    @RefersTo({\n        collection: 'section',\n        key: 'id',\n        isArray: true\n    })\n    sections: any[]\n}\n\nexport class CVRepository extends ORMOperations {\n    constructor() {\n        const ORM = addRepository(CVEntity);\n        super(ORM);\n    }\n}\n```\n\n```JavaScript\nimport { addRepository, Entity, IsRequired, ORMOperations, Allow, IsString } from 'mongo-strict';\n\n@Entity({ name: 'section' })\nclass SectionEntity {\n    @Allow()\n    @IsRequired()\n    @IsString()\n    sectionTitle: string;\n}\n\nexport class SectionRepository extends ORMOperations {\n    constructor() {\n        const ORM = addRepository(SectionEntity);\n        super(ORM);\n    }\n}\n```\n\nThen you are ready to start...\n\n```JavaScript\nimport { createConnection, initDBMap } from 'mongo-strict';\nimport { SectionRepository } from './section.repository';\nimport { CVRepository } from './cv.repository';\nimport { UserRepository } from './user.repository';\n\nconst start = async () =\u003e {\n    await createConnection({\n        uri: `mongodb://127.0.0.1:27017/fancy-cvs`\n    });\n\n    const userRepository = new UserRepository();\n    const cvRepository = new CVRepository();\n    const sectionRepository = new SectionRepository();\n\n    // Should be called after initializing all the repositories\n    await initDBMap();\n\n    let insertedUser;\n    try {\n        // You don't need to make any check before inserting or updating, mongo-strict will do that.\n        insertedUser = await userRepository.insertOne({\n            email: 'email@co.co',\n            name: 'mongo user',\n            country: 'mongolia',\n            cvs: []\n        });\n    } catch (e) { }\n\n    let insertedCV;\n    if (insertedUser) {\n        try {\n            insertedCV = await cvRepository.insertOne({\n                cvName: 'User CV 1',\n                currentPosition: 'Developer !',\n                sections: []\n            });\n            await userRepository.update(insertedUser.id).setOne({ cvs: [insertedCV.id] });\n        } catch (e) { }\n    }\n\n    if (insertedCV \u0026\u0026 insertedUser) {\n        const insertedSections: any = [];\n        for (let i = 0; i \u003c 6; i++) {\n            try {\n                const insertSection = await sectionRepository.insertOne({\n                    sectionTitle: `Section ${i + 1}`\n                });\n                insertedSections.push(insertSection);\n            } catch (e) { }\n        }\n\n        await cvRepository.update(insertedCV.id).setOne({ sections: insertedSections.map((section) =\u003e section.id) });\n    }\n\n    // This will fetch the user cvs and section with no need to make any lookups\n    const userData = await userRepository.findOne({\n        select: [\"id\", \"name\", \"cvs.cvName\", \"cvs.currentPosition\", \"cvs.sections.sectionTitle\"]\n    })\n\n    console.log(JSON.stringify(userData, null, 4));\n}\n\nstart();\n```\n\n**You can check more examples in the samples folder**\n\n## Create Connection\n\nYou should pass the connection options which should contains the connection uri.\n\nYou can pass the default repository Options which will be applied to the all repositories.\n\n```JavaScript\nawait createConnection({\n    uri: `mongodb://127.0.0.1:27017/fancy-cvs`\n}, repositoryOptions);\n```\n\nThe repository options will be applied to all added repositories.\n\n[Repository Options](#repository-options)\n\n## Add Repository\n\nYou can add a new repository by calling:\n\n```JavaScript\naddRepository(EntityClass, repositoryOptions)\n```\n\n### Repository Options\n\n| Option | Description |\n|--------|-------------|\n|    autoCreatedAt    |       default true      |\n|    autoUpdatedAt    |       default true      |\n|    createdAtKey    |      default 'createdAt'       |\n|    updatedAtKey    |        default 'updatedAt'     |\n|    maxFindTimeMS    |       default 60000      |\n|    debug    |       default false      |\n|    defaultSelectFields    |      default undefined       |\n|    cacheTimeout    |      default 1000 MS       |\n|    entityClassValidator    |      Entity Class Validator Options (defaults: {whitelist: true, forbidNonWhitelisted: true, validationError: { target: false }})       |\n| isAutoCreateUniqueIndex | You can force all unique keys implementation by creating a MongoDB unique index by setting isAutoCreateUniqueIndex to true |\n\n## Entity Class\n\nYou should pass the @Entity decorator before the Entity class and pass the collection name as a variable.\n\nThe entity class should contains all the entity keys.\n\nYou can add validations to every key and determine the default value, uniqueness and the references.\n\n```JavaScript\n@Entity({ name: 'user' })\nclass UserEntity {\n    @Allow()\n    @IsEmail(undefined, { message: \"The email should be valid :(\" })\n    @IsUnique({ isIgnoreCase: true })\n    email: string;\n\n    @Allow()\n    @IsRequired()\n    @MinLength(3)\n    name: string;\n}\n```\n\n### Entity Validation\n\n#### class-validator\n\nWe use [class-validator to validate the Entities](https://www.npmjs.com/package/class-validator#validation-decorators)\n\nSo you can call any validator class-validator provides, Examples:\n\n```JavaScript\n  @Length(10, 20)\n  @Contains('hello')\n  @IsInt()\n  @Min(0)\n  @Max(10)\n  @IsEmail()\n  @IsFQDN()\n  @IsDate()\n```\n\n#### IsRequired\n\nYou can mark any key as a required and pass the error message which will be passed if the key is not found.\n\n```JavaScript\n@IsRequired({message: 'This Key is required'})\nrequiredKey;\n```\n\n#### IsUnique\n\nYou can mark any key as unique key through the collection.\n\nYou can determine if you need it case sensitive or not.\n\n```JavaScript\n@IsUnique({message 'The use email should be unique', isIgnoreCase: boolean, isAutoCreateUniqueIndex: boolean}) // isIgnoreCase default false // isAutoCreateUniqueIndex default false\nuserEmail;\n```\n\n```note\nBy default, mongo-strict will implement the unique property manually by checking the existence of the unique key by a normal find query before the record insert/update.\n\nYou can force unique index implementation by creating a MongoDB unique index by setting isAutoCreateUniqueIndex to true\n```\n\n#### Default\n\nYou can pass the default value of any key\n\n```JavaScript\n@Default(0)\n@IsNumber()\ncounter;\n```\n\n#### RefersTo\n\nYou can mark any key as a reference key.\n\n```JavaScript\n@RefersTo({\n    collection: 'user'.\n    key: 'id',\n    as: 'user'\n})\nuser;\n```\n\n##### RefersTo Options\n\n| Option | Description |\n|--------|-------------|\n|    collection    | The collection which the key refers to|\n|    key    |       The key which the refer key refers to      |\n|    as    |       Select the reference as (defaults to the collection name)     |\n|    isArray    |      Determine if the key is an array (for example we may have array of users refer to many users with different Ids) (default false)      |\n|    maxDepth    |      Max Depth in case of circular references       |\n|    type    |       The relation type =\u003e  RELATION_TYPES.ONE_ONE - RELATION_TYPES.ONE_TO_MANY - RELATION_TYPES.MANY_TO_ONE - RELATION_TYPES.MANY_TO_MANY (default many to one) |\n|    message    |       The error message in case of insert or update refers to entity not found      |\n\n### Referers\n\nSuppose we have user and CV repositories but the CV repo is the container of the user Id.\n\n```JavaScript\n@Entity({ name: 'user' })\nclass UserEntity {\n    @Referers([{\n        collection: 'cv',\n        key: 'user',\n        as: 'cvs'\n    }])\n    id: string;\n\n    @Allow()\n    @IsEmail(undefined, { message: \"The email should be valid :(\" })\n    @IsUnique({ isIgnoreCase: true })\n    email: string;\n}\n\n@Entity({ name: 'cv' })\nclass CVEntity {\n    @Allow()\n    @IsRequired()\n    @IsString()\n    @RefersTo({\n        collection: 'user',\n        key: 'id'\n    })\n    user: string;\n\n    @Allow()\n    @IsRequired()\n    @IsString()\n    cvName: string;\n\n    @Allow()\n    @IsRequired()\n    @IsString()\n    currentPosition: string;\n}\n```\n\nWe can easly get the user of any CV by doing:\n\n```JavaScript\ncvRepository.find({select: ['user.email', 'user.id']})\n```\n\nBut in case if we need to get the user CVs we will need to use the @Referes().\n\nIn the User entity we have nothing indicates that this user has CV/s.\n\nFortunutly mongo-strict supports this operation by using the @Referers decorator like the above example.\n\nThen we can do:\n\n```JavaScript\nuserRepository.find({select: ['cvs.cvName']})\n```\n\n**The problem here that the user repository contains nothing about the CV repository so to get the user CVs the DB will have to loop through all the CV entities to get the CVs which refer to the wanted user which is not good for the performance**\n\n#### Referer Options\n\n| Option | Description |\n|--------|-------------|\n|    collection    | The collection which refers to the current key|\n|    key    |       The key in the referer's collection which refers to the current key    |\n|    as    |       Select the referer as     |\n\n**The @Referers Decorator accepts an array of referer Object**\n\n## Initialize the DB Map\n\nYou should call initDBMap() function after initializing all the repositories to inialize your database reference Map, Example:\n\n```Javascript\n    await createConnection({\n        uri: `mongodb://127.0.0.1:27017/fancy-cvs`\n    });\n\n    const userRepository = new UserRepository();\n    const cvRepository = new CVRepository();\n    const sectionRepository = new SectionRepository();\n\n    // Should be called after initializing all the repositories\n    await initDBMap();\n\n    // You can find the complete example in the Samples folder\n```\n\n## Operations\n\nmongo-strict supports the main Database operations and you can get the original collection for any operation we do not support until now.\n\n### find(findOptions: FindOptions)\n\nTo make a find query you have to pass the find options object which can contain where, select, sort...\n\n#### FindOptions\n\n|  findOption  |  Description  |\n|---|---|\n|  where  |  Filters the documents to pass only the documents that match the specified condition(s). (mongodb aggregation [$match](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match/)) |\n|  select  |  determine the field you want to select (can be array of strings or mongodb aggregation [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project/)) |\n|  sort  |  returns the documents in sorted order (mongodb aggregation [$sort](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort/)) |\n|  limit  |  Limits the number of the returned documents (mongodb aggregation [$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit/)) |\n|  skip  |  Skips over the specified number of documents (mongodb aggregation [$skip](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip/)) |\n| populate | populate reference entity or multiple reference entities (accepts string or array of strings) |\n| debug | true or false to print the final lookup DB method in the console, default = false |\n\n#### find example\n\nsuppose we have a collection of users and we want to get the email of the latest 10 users from a specific country...\n\n```JavaScript\n// returns array of documents\nconst usersEmail = await userRepository.find({\n    where: {country: \"Mongolia\"},\n    sort: {createdAt: -1},\n    limit: 10,\n    skip: 0,\n    select: [\"email\", \"id\"]\n})\n```\n\n### findAndCount(findOptions: FindOptions)\n\n```JavaScript\nconst {data, count} = await userRepository.findAndCount({\n    where: {country: \"Mongolia\"},\n    sort: {createdAt: -1},\n    limit: 10,\n    skip: 0,\n    select: [\"email\", \"id\"]\n})\n\n/* This will return {\n    data: Array of the returned documents,\n    count: the total count of user from mongolia\n} */\n```\n\n### findOne(findOptions: FindOptions)\n\nIt only finds one!\n\n```JavaScript\nconst latestUserEmail = await userRepository.findOne({\n    where: {country: \"Mongolia\"},\n    sort: {createdAt: -1},\n    select: [\"email\", \"id\"]\n})\n```\n\n### count(findOptions: FindOptions)\n\nIt will return the total number of documents applies the where object.\n\n```JavaScript\nconst usersCount = await userRepository.count({\n    where: {country: \"Mongolia\"}\n})\n```\n\n### findOneById(id: string, select)\n\nIt will find one document by its id and can select the wanted fields.\n\n```JavaScript\nconst user = await userRepository.findOneById(\"6309c6f839fc4980aeb34677\", [\"email\"])\n```\n\n### Query Caching\n\nYou can cache any query to get the results directly from the memory\n\n```JavaScript\nrepository.find({ where: { email: 'email@co.co' }, cache: true }) // the default cache Timeout is 1000 MS = 1 Second\n\nor\n\nrepository.find({ where: { email: 'email@co.co' }, cache: {timeout: 3000} })\n```\n\n### Query Builder\n\nYou can use the query builder for a better code organizing!\n\n```JavaScript\nrepo.queryBuilder()\n    .where({isDeleted: false})\n    .select([\"email\"])\n    .sort({id: -1})\n    .limit(10)\n    .cache(true)\n    .find();\n```\n\n### Find reference Entities\n\nSuppose we have user and CV repositories\n\n```JavaScript\n@Entity({ name: 'cv' })\nclass CVEntity {\n    @Allow()\n    @IsRequired()\n    @IsString()\n    cvName: string;\n\n    @Allow()\n    @IsRequired()\n    @IsString()\n    currentPosition: string;\n}\n\n@Entity({ name: 'user' })\nclass UserEntity {\n    @Allow()\n    @IsEmail(undefined, { message: \"The email should be valid :(\" })\n    @IsUnique({ isIgnoreCase: true })\n    email: string;\n\n    @Allow()\n    @IsArray()\n    @RefersTo({\n        collection: 'cv',\n        key: 'id',\n        isArray: true\n    })\n    cvs: any[];\n}\n```\n\nHere the user entity contains the CVs IDs (@RefersTo({collection: 'cv', .... }))\n\nTo get the all the user CVs we can easly do:\n\n```JavaScript\nuserRepository.find({select: ['cvs.cvName']})\n```\n\nOnce we select an inner value of the CVs, that will notify the mongo-strict to get the referenced entity.\n**We can select, match and sort by cvs.cvName or any cvs inner key**\nOr we can user populate\n\n### Populate\n\nIn the above example we can do:\n\n```JavaScript\nuserRepository.find({populate: ['cvs']});\n```\n\nThis will return the user caontainig the complete cvs data\n\nYou can populate multipe entites: \n\n```JavaScript\nuserRepository.find({populate: ['cvs', 'ref1', 'ref2']});\n```\n\nOnce can populate the referenceies by any depth:\n\n```JavaScript\nuserRepository.find({populate: ['cvs.ref.ref.ref']});\n// this will poplate all the sub referncies\n```\n\n### insertOne\n\nmongo-strict uses a simple insertOne operation and returns the inserted document.\n\n```JavaScript\nconst insertedUser = await userRepository.insertOne({\n                    email: 'email@co.co',\n                    name: 'mongo user',\n                    country: 'mongolia'\n                });\n\nconst insertedCV = await cvRepository.insertOne({\n                    user: insertedUser.id,\n                    cvName: 'User CV 1',\n                    currentPosition: 'Developer !'\n                });\n```\n\nYou can simply insert an Object contains your entity data.\n\nmongo-strict will validate the inserted entity and check if any uniques key are previously existing or not, check for the existence of the reference keys and all the other checks, in case of any any error it will throw an error.\n\nWe doesn't fully support the mongoDB advanced insert operations.\n\n#### validateInsertData\n\nIf you want to validate the date before inserting you can call validateInsertData\n\n```JavaScript\nconst isValidUserData = await userRepository.validateInsertData({\n                    email: 'email@co.co',\n                    name: 'mongo user',\n                    country: 'mongolia'\n                });\n\n// It will not insert the data into the repository\n// Returns true in case of valid data\n// Throws error in case of invalid data\n```\n\n### Update(filter: object | id: string)\n\nTo perform an update operation you need to call the Update function with the update filter or the id of the entity you want to update.\n\nThis will return 3 function you will need to pass the updated data/entity to:\n\n#### 1- setOne(data)\n\n- You need to pass just the keys you want to update in the entity.\n- Updates only one matching document in the collection that match the filter.\n- Returns the full updated Entity\n\n```JavaScript\nconst updatedUser = await userRepository.update({email: 'email@co.co'}).setOne({\n                    name: 'updated mongo user',\n                  });\n\nOr\n\nconst updatedUser = await userRepository.update(user.id). setOne({\n                    name: 'updated mongo user',\n                  });\n\n```\n\n#### 2- setMany(data)\n\nupdates all matching documents in the collection that match the filter.\n\n**The method returns a document that contains:**\n\n- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.\n- matchedCount containing the number of matched documents.\n- modifiedCount containing the number of modified documents.\n- upsertedId containing the id for the upserted document\n\n```JavaScript\nawait userRepository.update({}).setMany({\n    isDeleted: false\n});\n// the will set isDelete to false in all users in the collection\n```\n\n#### 3- replaceOne(completeEntityData)\n\nreplaceOne() replaces the first matching document in the collection that matches the filter, using the replacement document\n\n**Returns a document containing:**\n\n- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.\n- matchedCount containing the number of matched documents.\n- modifiedCount containing the number of modified documents.\n- upsertedId containing the id for the upserted document.\n\n```JavaScript\nawait userRepository.update(user.id).replaceOne({\n    email: 'newEmail@co.com',\n    name: 'mongo user :)',\n    country: 'mongolia'\n});\n```\n\n### Errors Handling\n\nOur goal in mongo-strict is to unify the way of throwing the exceptions and give you the full control of the error message to make you able to catch the error then pass it as a response directly with no more code.\n\n#### Invalid data error\n\nFor example if you marked a field as @IsEmail()\n\n```JavaScript\n@Entity({ name: 'user' })\nclass UserEntity {\n    @Allow()\n    @IsEmail(undefined, { message: \"The email should be valid :(\" })\n    @IsUnique({ isIgnoreCase: true, message: 'The email should be unique' })\n    email: string;\n}\n```\n\nThen you inserted an invalid email in insert or update it will throw:\n\n```JavaScript\ntry {\n    // insert invalid email\n} catch(e) {\n    console.log(e);\n\n    // {\n    //     message: 'Invalid Data Found',\n    //     invalidKeys: ['email'],\n    //     errorMessages: ['The email should be valid :(']\n    // }\n}\n```\n\n#### Existing Unique Keys\n\nIf you marked the email as a unique key and you tried to insert an email which is already exists it will throw:\n\n```JavaScript\ntry {\n    // insert already exists email\n} catch(e) {\n    console.log(e);\n\n    // {\n    //     message: 'Existing unique keys',\n    //     existingUniqueKeys: ['email'],\n    //     errorMessages: ['The email should be unique']\n    // }\n}\n```\n\n#### Not Found Reference Keys\n\nIf you marked any field as a reference to another collection and you inserted a not found reference it will throw:\n\n```JavaScript\ntry {\n    // insert not found reference\n} catch(e) {\n    console.log(e);\n\n    // {\n    //     message: 'Not found reference keys',\n    //     missedReferenceKeys: ['user'],\n    //     errorMessages: ['The user is not found']\n    // }\n}\n```\n\n### deleteOne(filter: any | id: string)\n\nDeletes the first document that matches the filter. Use a field that is part of a unique index such as id for precise deletions.\n\n**We just call the mongoDB deleteOne, in the future we will support sql DBs onDelete...**\n\n**Returns a document containing:**\n\n- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.\n- deletedCount containing the number of deleted documents\n\n### deleteMany(filter: any | ids: string[])\n\nDeletes documents one at a time. If the primary node fails during a deleteMany() operation, documents that were not yet deleted from secondary nodes are not deleted from the collection.\n\n**We just call the mongoDB deleteMany, in the future we will support sql DBs onDelete...**\n\n**Returns a document containing:**\n\n- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.\n- deletedCount containing the number of deleted documents\n\n### getCollection()\n\nIf you want to make any operation we don't support until now you can get the MongoDB collection and run the orginal mongo query\n\n```JavaScript\nuserRepository.getCollection().find({}).limit(10).toArray();\n```\n\n### getDB()\n\nIf you want to drop the DB or make any DB operation you can use getDB()\n\n```JavaScript\nconst db = getDB();\nawait db.dropDatabase();\n```\n\n### getConnectionManager()\n\nIf you want to close the connection any connection operation you can use getConnectionManager()\n\n```JavaScript\nconst connection = getConnectionManager();\nconnection.close();\n```\n\n## Roadmap\n\n- InsertMany()\n- ReplaceMany()\n- onDelete() // strict, cascade, setNull ...\n- lifeCycle\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmib-kamel%2Fmongo-strict","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmib-kamel%2Fmongo-strict","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmib-kamel%2Fmongo-strict/lists"}