{"id":14969916,"url":"https://github.com/loopbackio/loopback-connector-mongodb","last_synced_at":"2026-01-15T22:20:58.672Z","repository":{"id":9174865,"uuid":"10975056","full_name":"loopbackio/loopback-connector-mongodb","owner":"loopbackio","description":"The official MongoDB connector for the LoopBack framework.","archived":false,"fork":false,"pushed_at":"2026-01-12T18:12:11.000Z","size":3697,"stargazers_count":186,"open_issues_count":27,"forks_count":240,"subscribers_count":56,"default_branch":"master","last_synced_at":"2026-01-13T03:35:49.529Z","etag":null,"topics":["hacktoberfest","loopback","loopback4","mongodb","nodejs"],"latest_commit_sha":null,"homepage":"https://loopback.io/doc/en/lb4/MongoDB-connector","language":"JavaScript","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/loopbackio.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2013-06-26T18:04:58.000Z","updated_at":"2026-01-12T18:11:16.000Z","dependencies_parsed_at":"2024-02-13T10:27:21.649Z","dependency_job_id":"8c736435-413e-465c-8994-4d946b19fc14","html_url":"https://github.com/loopbackio/loopback-connector-mongodb","commit_stats":{"total_commits":496,"total_committers":91,"mean_commits":5.450549450549451,"dds":0.7298387096774194,"last_synced_commit":"fe4a2f9261cd3968fe8165b84e1be3c29cbe9a42"},"previous_names":["strongloop/loopback-connector-mongodb"],"tags_count":103,"template":false,"template_full_name":null,"purl":"pkg:github/loopbackio/loopback-connector-mongodb","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Floopback-connector-mongodb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Floopback-connector-mongodb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Floopback-connector-mongodb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Floopback-connector-mongodb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loopbackio","download_url":"https://codeload.github.com/loopbackio/loopback-connector-mongodb/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Floopback-connector-mongodb/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28472626,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-15T22:13:38.078Z","status":"ssl_error","status_checked_at":"2026-01-15T22:12:11.737Z","response_time":62,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6: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":["hacktoberfest","loopback","loopback4","mongodb","nodejs"],"created_at":"2024-09-24T13:42:40.955Z","updated_at":"2026-01-15T22:20:58.666Z","avatar_url":"https://github.com/loopbackio.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# loopback-connector-mongodb\n\nThe official MongoDB connector for the LoopBack framework.\n\n## Installation\n\nIn your application root directory, enter this command to install the connector:\n\n```sh\nnpm install loopback-connector-mongodb --save\n```\n\nThis installs the module from npm and adds it as a dependency to the application's `package.json` file.\n\nIf you create a MongoDB data source using the data source generator as described below, you don't have to do this, since the generator will run `npm install` for you.\n\n## Supported versions\n\n**Starting from the version 6.0.0, this connector is no longer compatible with LoopBack 3. Please use the latest 5.x version in your LoopBack 3 applications.**\n\nThis module adopts the [Module Long Term Support (LTS)](http://github.com/CloudNativeJS/ModuleLTS) policy, with the following End Of Life (EOL) dates:\n\n| Version    | Status               | Published | EOL                  | LoopBack | Juggler  |\n| ---------- | -------------------- | --------- | -------------------- | ---------|----------|\n| 6.x        | Current              | Mar 2021  | Apr 2028 _(minimum)_ | 4        | 4.x      |\n| 5.x        | End-of-Life          | Jun 2019  | Apr 2023             | 3, 4     | 3.x, 4.x |\n| 4.x        | End-of-Life          | Nov 2018  | Apr 2021             | 3, 4     | 3.x, 4.x |\n\n## Creating a MongoDB data source\n\nFor LoopBack 4 users, use the LB4 [Command-line interface](https://loopback.io/doc/en/lb4/Command-line-interface.html) to generate a DataSource with MongoDB connector to your LB4 application. Run [`lb4 datasource`](https://loopback.io/doc/en/lb4/DataSource-generator.html), it will prompt for configurations such as host, post, etc. that are required to connect to a MongoDB database.\n\nAfter setting it up, the configuration can be found under `src/datasources/\u003cDataSourceName\u003e.datasource.ts`, which would look like this:\n\n```ts\nconst config = {\n  name: 'db',\n  connector: 'mongodb',\n  url: '',\n  host: 'localhost',\n  port: 27017,\n  user: '',\n  password: '',\n  database: 'testdb',\n};\n```\n\nIf your username or password contains special characters like `@`, `$` etc, encode the whole\nusername or password using [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).\n\nEg: `pa$$wd` would become `pa%24%24wd`.\n\n### Connection properties\n\n| Property   | Type\u0026nbsp;\u0026nbsp; | Description                                                                                                |\n| ---------- | ---------------- | ---------------------------------------------------------------------------------------------------------- |\n| connector  | String           | Connector name, either `\"loopback-connector-mongodb\"` or `\"mongodb\"`.                                      |\n| database   | String           | Database name                                                                                              |\n| host       | String           | Database host name                                                                                         |\n| name       | String           | Name of the datasource in the app                                                                          |\n| password   | String           | Password to connect to database                                                                            |\n| port       | Number           | Database TCP port                                                                                          |\n| url        | String           | Connection URL of form `mongodb://user:password@host/db`. Overrides other connection settings (see below). |\n| user       | String           | Username to connect to database                                                                            |\n| authSource | String           | Optional. Authentification database name. Usually `\"admin\"` value.                                         |\n\nIf you run a MongoDB with authentification ([Docker's example here](https://github.com/docker-library/docs/tree/master/mongo#mongo_initdb_root_username-mongo_initdb_root_password)), you need to specify which database to authenticate against. More details can be found in [MongoDB documentation on Authentification Methods](https://docs.mongodb.com/manual/core/authentication/#authentication-methods). The default value is usually `\"admin\"`, like in the official docker image.\n\n**NOTE**: In addition to these properties, you can use additional Single Server Connection parameters supported by [`node-mongodb-native`](http://mongodb.github.io/node-mongodb-native/core/driver/reference/connecting/connection-settings/).\n\n### Additional properties\n\n\u003ctable\u003e\n  \u003cthead\u003e\n  \u003ctr\u003e\n    \u003cth width=\"160\"\u003eProperty\u003c/th\u003e\n    \u003cth width=\"90\"\u003eType\u003c/th\u003e\n    \u003cth\u003eDefault\u003c/th\u003e\n    \u003cth\u003eDescription\u003c/th\u003e\n  \u003c/tr\u003e\n  \u003c/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eallowExtendedOperators\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003e\u003ccode\u003efalse\u003c/code\u003e\u003c/td\u003e\n      \u003ctd\u003eSet to \u003ccode\u003etrue\u003c/code\u003e to enable using MongoDB operators such as \u003ccode\u003e$currentDate, $inc, $max, $min, $mul, $rename, $setOnInsert, $set, $unset, $addToSet, $pop, $pullAll, $pull, $push\u003c/code\u003e, and \u003ccode\u003e$bit\u003c/code\u003e. See \u003ca href=\"https://loopback.io/doc/en/lb4/MongoDB-connector.html#update-operators\" class=\"external-link\" rel=\"nofollow\"\u003eUpdate Operators\u003c/a\u003e section below\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eenableGeoIndexing\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003e\u003ccode\u003efalse\u003c/code\u003e\u003c/td\u003e\n      \u003ctd\u003eSet to \u003ccode\u003etrue\u003c/code\u003e to enable 2d sphere indexing for model properties of type \u003ccode\u003eGeoPoint\u003c/code\u003e. This allows for indexed \u003ccode\u003enear\u003c/code\u003e queries.\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003elazyConnect\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003e\u003ccode\u003efalse\u003c/code\u003e\u003c/td\u003e\n      \u003ctd\u003eWhen set to \u003ccode\u003etrue\u003c/code\u003e, the database instance will not be attached to the datasource and the connection is deferred. It will try to establish the connection automatically once users hit the endpoint. If the MongoDB server is offline, the app will start, however, the endpoints will not work.\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003edisableDefaultSort\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003e\u003ccode\u003efalse\u003c/code\u003e\u003c/td\u003e\n      \u003ctd\u003eSet to \u003ccode\u003etrue\u003c/code\u003e to disable the default sorting behavior on \u003ccode\u003eid\u003c/code\u003e column, this will help performance using indexed columns available in MongoDB.\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003ecollation\u003c/td\u003e\n      \u003ctd\u003eString\u003c/td\u003e\n      \u003ctd\u003eN/A\u003c/td\u003e\n      \u003ctd\u003eSpecify language-specific rules for string comparison, such as rules for letter-case and accent marks. See \u003ca href=\"https://docs.mongodb.com/manual/reference/collation/\"\u003eMongoDB documentation\u003c/a\u003e for details. It can also be used to create \u003ca href=\"https://docs.mongodb.com/manual/core/index-case-insensitive/\"\u003ecase insensitive indexes\u003c/a\u003e.\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\n### Setting the url property in datasource.ts\n\nYou can set the `url` property to a connection URL in `\u003cdatasourceName\u003e.datasources.ts` to override individual connection parameters such as `host`, `user`, and `password`. E.g `loopback:pa55w0rd@localhost:27017/testdb`.\n\n### Using the mongodb+srv protocol\n\nMongoDB supports a protocol called `mongodb+srv` for connecting to replica sets without having to give the hostname of every server in the replica set.\nTo use `mongodb+srv` as the protocol set the `protocol` connection property in the datasource.json to `mongodb+srv`. For example:\n\n```ts\nconst config = {\n  name: 'db',\n  connector: 'mongodb',\n  host: 'myserver',\n  database: 'testdb',\n  protocol: 'mongodb+srv',\n};\n```\n\nNote: the port is not specified when using the `mongodb+srv` protocol and will be ignored if given.\n\n### TLS/SSL Connections\n\nNote: SSL options deprecated since MongoDB 4.2\n\n```ts\nconst config = {\n  name: 'db',\n  connector: 'mongodb',\n  url: '',\n  host: 'localhost',\n  port: 27017,\n  user: '',\n  password: '',\n  database: 'testdb',\n  tls: true,\n  tlsCertificateKeyFile: '/local/path/to/pem-file',\n  tlsCAFile: '/local/path/to/ca-file',\n};\n```\n\n## Security Considerations\n\nMongoDB Driver allows the `$where` operator to pass in JavaScript to execute on the Driver which can be used for NoSQL Injection. See [MongoDB: Server-side JavaScript](https://docs.mongodb.com/manual/core/server-side-javascript/) for more on this MongoDB feature.\n\nTo protect users against this potential vulnerability, LoopBack will automatically **remove** the `$where` and `mapReduce` operators from a query before it's passed to the MongoDB Driver. If you need to use these properties from within LoopBack programmatically, you can disable the sanitization by passing in an `options` object with `disableSanitization` property set to `true`.\n\n**Example:**\n\n```ts\nawait PostRepository.find(\n  { where: { $where: \"function() { /*JS function here*/}\" } },\n  { disableSanitization: true }\n);\n```\n\n## Type mappings\n\nSee [LoopBack 4 types](http://loopback.io/doc/en/lb4/LoopBack-types.html) (or [LoopBack 3 types](http://loopback.io/doc/en/lb3/LoopBack-types.html)) for details on LoopBack's data types.\n\n### LoopBack to MongoDB types\n\nType conversion is mainly handled by MongoDB. See ['node-mongodb-native'](http://mongodb.github.io/node-mongodb-native/) for details.\n\n## Update Operators\n\nExcept the comparison and logical operators LoopBack supports in the [operator list](https://loopback.io/doc/en/lb4/Where-filter.html#operators) of `Where` filter, you can also enable [MongoDB update operators](https://docs.mongodb.com/manual/reference/operator/update/) for `update*` methods by setting the flag `allowExtendedOperators` to `true` in the datasource configuration.\n\nHere is an example of updating the price for all the products under category `furniture` if their current price is lower than 100:\n\n```\nawait productRepo.updateAll({ $max: { price: 100 }}, { category: {eq: 'furniture'} // where clause goes in here });\n```\n\n{% include tip.html content=\"you **will not** need the dollar sign `'$'` for operators in the Where\nclause.\" %}\n\n## Handling ObjectId\n\nMongoDB uses `ObjectId` for its primary key, which is an object instead of a\nstring. In queries, string values must be cast to `ObjectId`, otherwise they are\nnot considered as the same value. Therefore, you might want to specify the data\ntype of properties to enforce `ObjectId` coercion. Such coercion would make sure\nthe property value converts from ObjectId-like string to `ObjectId` when it\naccesses to the database and converts `ObjectId` to ObjectId-like string when\nthe app gets back the value. (An ObjectId-like string is a string that has length 12 or 24 and has the format of an `ObjectId` i.e /^[0-9a-fA-F]{24}\\$/.)\n\nLoopBack provides two scopes to handle such coercion: per model or per property. Please check the following to see which configuration meets your requirements.\n\n{% include important.html content=\"please make sure you are using `loopback-connector-mongodb` package version 5.2.1\nor above to handle `ObjectId` properly.\" %}\n\n- No `ObjectId` coercion: CRUD operations can be operated with non-ObjectId-like\n  string or ObjectId-like string ids.\n\n- Enforce `ObjectId` coercion: the property value can only be `ObjectId` or\n  ObjectId-like string, otherwise it will be rejected.\n\nEnforcing `ObjectId` coercion can be done by setting the flag\n`strictObjectIDCoercion` in the **model definition** or by specifying\n`dataType: ObjecId` in the **property definition**.\n\n### Model scope\n\nThis scope would do the conversion for all properties in the model.\n\n```ts\n@model({settings: {\n  strictObjectIDCoercion: true\n}})\nexport class User extends Entity {\n@property({\n    type: 'string',\n    id: true,\n  })\n  id: string;\n...\n}\n```\n\n### Property scope\n\nThis scope would only convert an ObjectId-like string to `ObjectId` with a certain property in the model.\n\n```ts\n@property({\n    type: 'string',\n    id: true,\n    mongodb: {dataType: 'ObjectId'}\n  }\n  id: string;\n```\n\nAlso notice that for RELATIONS, if the primary key/source key has set to enforce ObjectId coercion\n(no matter by `strictObjectIDCoercion: true` or `dataType: 'ObjectId'`). The corresponding foreign key will need to have it\nset as well to make sure relations work smoothly.\n\n```ts\n@model()\nexport class User extends Entity {\n// source key\n@property({\n    type: 'string',\n    id: true,\n    mongodb: {dataType: 'ObjectId'}\n  })\n  id: string;\n...\n}\n\n@model(// )\nexport class Address extends Entity {\n  ...\n  // foreign key\n  @belongsTo(() =\u003e User,\n   {}, //relation metadata goes in here\n   {// property definition goes in here\n    mongodb: {dataType: 'ObjectId'}\n  })\n  UserId: string;\n}\n```\n\n## Customize collection/field names\n\n`loopback-connector-mongodb` allows you to have different collection and field names from the models. Such configurations can be added to the model definition and the property definition respectively as `mongodb:{ \u003cfield\u003e: \u003ccustomValue\u003e}`. For example, the following setting would define a collection with custom name `Custom_Collection_User`, and it has a custom field name `Custom_Name` in the database:\n\n{% include code-caption.html content=\"/src/models/User.model.ts\" %}\n\n```ts\n@model({\n  settings: {\n    // model definition goes in here\n    mongodb: { collection: \"Custom_Collection_User\" },\n  },\n})\nexport class User extends Entity {\n  @property({\n    type: \"string\",\n    id: true,\n    generated: true,\n  })\n  id: string;\n\n  @property({\n    type: \"string\",\n    mongodb: {\n      fieldName: \"Custom_Name\",\n    },\n  })\n  name?: string;\n}\n```\n\n{% include important.html content=\"Since in MongoDB `_id` is reserved for the primary key, LoopBack **does not** allow customization of the field name for the id property. Please use `id` as is. Customizing the id property would cause errors.\" %}\n\n## Running tests\n\n### Own instance\n\nIf you have a local or remote MongoDB instance and would like to use that to run the test suite, use the following command:\n\n- Linux\n\n```bash\nMONGODB_HOST=\u003cHOST\u003e MONGODB_PORT=\u003cPORT\u003e MONGODB_DATABASE=\u003cDATABASE\u003e CI=true npm test\n```\n\n- Windows\n\n```bash\nSET MONGODB_HOST=\u003cHOST\u003e SET MONGODB_PORT=\u003cPORT\u003e SET MONGODB_DATABASE=\u003cDATABASE\u003e SET CI=true npm test\n```\n\n### Docker\n\nIf you do not have a local MongoDB instance, you can also run the test suite with very minimal requirements.\n\n- Assuming you have [Docker](https://docs.docker.com/engine/installation/) installed, run the following script which would spawn a MongoDB instance on your local:\n\n```bash\nsource setup.sh \u003cHOST\u003e \u003cPORT\u003e \u003cDATABASE\u003e\n```\n\nwhere `\u003cHOST\u003e`, `\u003cPORT\u003e` and `\u003cDATABASE\u003e` are optional parameters. The default values are `localhost`, `27017` and `testdb` respectively.\n\n- Run the test:\n\n```bash\nnpm test\n```\n\n### Leak detection\n\nTests run for 100 iterations by default, but can be increased by setting the\nenv var `ITERATIONS`.\n\n```\nmake leak-detection # run 100 iterations (default)\n```\n\nor\n\n```\nITERATIONS=1000 make leak-detection # run 1000 iterations\n```\n\n## Running benchmarks\n\n**Benchmarks must be run on a Unix-like operating system.**\n\n```\nmake benchmarks\n```\n\nThe results will be output in `./benchmarks/results.md`.\n\n## Release notes\n\n- 1.1.7 - Do not return MongoDB-specific `_id` to client API, except if specifically specified in the model definition\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floopbackio%2Floopback-connector-mongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floopbackio%2Floopback-connector-mongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floopbackio%2Floopback-connector-mongodb/lists"}