- Notifications
You must be signed in to change notification settings - Fork241
The official MongoDB connector for the LoopBack framework.
License
loopbackio/loopback-connector-mongodb
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The official MongoDB connector for the LoopBack framework.
In your application root directory, enter this command to install the connector:
npm install loopback-connector-mongodb --save
This installs the module from npm and adds it as a dependency to the application's package.json
file.
If 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 runnpm install
for you.
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.
This module adopts theModule Long Term Support (LTS) policy, with the following End Of Life (EOL) dates:
Version | Status | Published | EOL | LoopBack | Juggler |
---|---|---|---|---|---|
6.x | Current | Mar 2021 | Apr 2028(minimum) | 4 | 4.x |
5.x | End-of-Life | Jun 2019 | Apr 2023 | 3, 4 | 3.x, 4.x |
4.x | End-of-Life | Nov 2018 | Apr 2021 | 3, 4 | 3.x, 4.x |
For LoopBack 4 users, use the LB4Command-line interface to generate a DataSource with MongoDB connector to your LB4 application. Runlb4 datasource
, it will prompt for configurations such as host, post, etc. that are required to connect to a MongoDB database.
After setting it up, the configuration can be found undersrc/datasources/<DataSourceName>.datasource.ts
, which would look like this:
constconfig={name:'db',connector:'mongodb',url:'',host:'localhost',port:27017,user:'',password:'',database:'testdb',};
If your username or password contains special characters like@
,$
etc, encode the wholeusername or password usingencodeURIComponent.
Eg:pa$$wd
would becomepa%24%24wd
.
Property | Type | Description |
---|---|---|
connector | String | Connector name, either"loopback-connector-mongodb" or"mongodb" . |
database | String | Database name |
host | String | Database host name |
name | String | Name of the datasource in the app |
password | String | Password to connect to database |
port | Number | Database TCP port |
url | String | Connection URL of formmongodb://user:password@host/db . Overrides other connection settings (see below). |
user | String | Username to connect to database |
authSource | String | Optional. Authentification database name. Usually"admin" value. |
If you run a MongoDB with authentification (Docker's example here), you need to specify which database to authenticate against. More details can be found inMongoDB documentation on Authentification Methods. The default value is usually"admin"
, like in the official docker image.
NOTE: In addition to these properties, you can use additional Single Server Connection parameters supported by node-mongodb-native
.
Property | Type | Default | Description |
---|---|---|---|
allowExtendedOperators | Boolean | false | Set totrue to enable using MongoDB operators such as$currentDate, $inc, $max, $min, $mul, $rename, $setOnInsert, $set, $unset, $addToSet, $pop, $pullAll, $pull, $push , and$bit . SeeUpdate Operators section below |
enableGeoIndexing | Boolean | false | Set totrue to enable 2d sphere indexing for model properties of typeGeoPoint . This allows for indexednear queries. |
lazyConnect | Boolean | false | When set totrue , 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. |
disableDefaultSort | Boolean | false | Set totrue to disable the default sorting behavior onid column, this will help performance using indexed columns available in MongoDB. |
collation | String | N/A | Specify language-specific rules for string comparison, such as rules for letter-case and accent marks. SeeMongoDB documentation for details. It can also be used to createcase insensitive indexes. |
You can set theurl
property to a connection URL in<datasourceName>.datasources.ts
to override individual connection parameters such ashost
,user
, andpassword
. E.gloopback:pa55w0rd@localhost:27017/testdb
.
MongoDB supports a protocol calledmongodb+srv
for connecting to replica sets without having to give the hostname of every server in the replica set.To usemongodb+srv
as the protocol set theprotocol
connection property in the datasource.json tomongodb+srv
. For example:
constconfig={name:'db',connector:'mongodb',host:'myserver',database:'testdb',protocol:'mongodb+srv',};
Note: the port is not specified when using themongodb+srv
protocol and will be ignored if given.
Note: SSL options deprecated since MongoDB 4.2
constconfig={name:'db',connector:'mongodb',url:'',host:'localhost',port:27017,user:'',password:'',database:'testdb',tls:true,tlsCertificateKeyFile:'/local/path/to/pem-file',tlsCAFile:'/local/path/to/ca-file',};
MongoDB Driver allows the$where
operator to pass in JavaScript to execute on the Driver which can be used for NoSQL Injection. SeeMongoDB: Server-side JavaScript for more on this MongoDB feature.
To protect users against this potential vulnerability, LoopBack will automaticallyremove the$where
andmapReduce
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 anoptions
object withdisableSanitization
property set totrue
.
Example:
awaitPostRepository.find({where:{$where:"function() { /*JS function here*/}"}},{disableSanitization:true});
SeeLoopBack 4 types (orLoopBack 3 types) for details on LoopBack's data types.
Type conversion is mainly handled by MongoDB. See'node-mongodb-native' for details.
Except the comparison and logical operators LoopBack supports in theoperator list ofWhere
filter, you can also enableMongoDB update operators forupdate*
methods by setting the flagallowExtendedOperators
totrue
in the datasource configuration.
Here is an example of updating the price for all the products under categoryfurniture
if their current price is lower than 100:
await productRepo.updateAll({ $max: { price: 100 }}, { category: {eq: 'furniture'} // where clause goes in here });
{% include tip.html content="youwill not need the dollar sign'$'
for operators in the Whereclause." %}
MongoDB usesObjectId
for its primary key, which is an object instead of astring. In queries, string values must be cast toObjectId
, otherwise they arenot considered as the same value. Therefore, you might want to specify the datatype of properties to enforceObjectId
coercion. Such coercion would make surethe property value converts from ObjectId-like string toObjectId
when itaccesses to the database and convertsObjectId
to ObjectId-like string whenthe app gets back the value. (An ObjectId-like string is a string that has length 12 or 24 and has the format of anObjectId
i.e /^[0-9a-fA-F]{24}$/.)
LoopBack provides two scopes to handle such coercion: per model or per property. Please check the following to see which configuration meets your requirements.
{% include important.html content="please make sure you are usingloopback-connector-mongodb
package version 5.2.1or above to handleObjectId
properly." %}
No
ObjectId
coercion: CRUD operations can be operated with non-ObjectId-likestring or ObjectId-like string ids.Enforce
ObjectId
coercion: the property value can only beObjectId
orObjectId-like string, otherwise it will be rejected.
EnforcingObjectId
coercion can be done by setting the flagstrictObjectIDCoercion
in themodel definition or by specifyingdataType: ObjecId
in theproperty definition.
This scope would do the conversion for all properties in the model.
@model({settings:{strictObjectIDCoercion:true}})exportclassUserextendsEntity{@property({type:'string',id:true,})id:string;...}
This scope would only convert an ObjectId-like string toObjectId
with a certain property in the model.
@property({type:'string',id:true,mongodb:{dataType:'ObjectId'}}id: string;
Also notice that for RELATIONS, if the primary key/source key has set to enforce ObjectId coercion(no matter bystrictObjectIDCoercion: true
ordataType: 'ObjectId'
). The corresponding foreign key will need to have itset as well to make sure relations work smoothly.
@model()exportclassUserextendsEntity{// source key@property({type:'string',id:true,mongodb:{dataType:'ObjectId'}})id:string;...}@model(// )exportclassAddressextendsEntity{ ...// foreign key @belongsTo(()=>User,{},//relation metadata goes in here{// property definition goes in heremongodb:{dataType:'ObjectId'}})UserId: string;}
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 asmongodb:{ <field>: <customValue>}
. For example, the following setting would define a collection with custom nameCustom_Collection_User
, and it has a custom field nameCustom_Name
in the database:
{% include code-caption.html content="/src/models/User.model.ts" %}
@model({settings:{// model definition goes in heremongodb:{collection:"Custom_Collection_User"},},})exportclassUserextendsEntity{ @property({type:"string",id:true,generated:true,})id:string; @property({type:"string",mongodb:{fieldName:"Custom_Name",},})name?:string;}
{% include important.html content="Since in MongoDB_id
is reserved for the primary key, LoopBackdoes not allow customization of the field name for the id property. Please useid
as is. Customizing the id property would cause errors." %}
If you have a local or remote MongoDB instance and would like to use that to run the test suite, use the following command:
- Linux
MONGODB_HOST=<HOST> MONGODB_PORT=<PORT> MONGODB_DATABASE=<DATABASE> CI=true npmtest
- Windows
SET MONGODB_HOST=<HOST> SET MONGODB_PORT=<PORT> SET MONGODB_DATABASE=<DATABASE> SET CI=true npmtest
If you do not have a local MongoDB instance, you can also run the test suite with very minimal requirements.
- Assuming you haveDocker installed, run the following script which would spawn a MongoDB instance on your local:
source setup.sh<HOST><PORT><DATABASE>
where<HOST>
,<PORT>
and<DATABASE>
are optional parameters. The default values arelocalhost
,27017
andtestdb
respectively.
- Run the test:
npmtest
Tests run for 100 iterations by default, but can be increased by setting theenv varITERATIONS
.
make leak-detection # run 100 iterations (default)
or
ITERATIONS=1000 make leak-detection # run 1000 iterations
Benchmarks must be run on a Unix-like operating system.
make benchmarks
The results will be output in./benchmarks/results.md
.
- 1.1.7 - Do not return MongoDB-specific
_id
to client API, except if specifically specified in the model definition
About
The official MongoDB connector for the LoopBack framework.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.