Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The official MongoDB connector for the LoopBack framework.

License

NotificationsYou must be signed in to change notification settings

loopbackio/loopback-connector-mongodb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

The official MongoDB connector for the LoopBack framework.

Installation

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.

Supported versions

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:

VersionStatusPublishedEOLLoopBackJuggler
6.xCurrentMar 2021Apr 2028(minimum)44.x
5.xEnd-of-LifeJun 2019Apr 20233, 43.x, 4.x
4.xEnd-of-LifeNov 2018Apr 20213, 43.x, 4.x

Creating a MongoDB data source

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.

Connection properties

PropertyType  Description
connectorStringConnector name, either"loopback-connector-mongodb" or"mongodb".
databaseStringDatabase name
hostStringDatabase host name
nameStringName of the datasource in the app
passwordStringPassword to connect to database
portNumberDatabase TCP port
urlStringConnection URL of formmongodb://user:password@host/db. Overrides other connection settings (see below).
userStringUsername to connect to database
authSourceStringOptional. 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.

Additional properties

PropertyTypeDefaultDescription
allowExtendedOperatorsBooleanfalseSet 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
enableGeoIndexingBooleanfalseSet totrue to enable 2d sphere indexing for model properties of typeGeoPoint. This allows for indexednear queries.
lazyConnectBooleanfalseWhen 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.
disableDefaultSortBooleanfalseSet totrue to disable the default sorting behavior onid column, this will help performance using indexed columns available in MongoDB.
collationStringN/ASpecify 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.

Setting the url property in datasource.ts

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.

Using the mongodb+srv protocol

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.

TLS/SSL Connections

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',};

Security Considerations

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});

Type mappings

SeeLoopBack 4 types (orLoopBack 3 types) for details on LoopBack's data types.

LoopBack to MongoDB types

Type conversion is mainly handled by MongoDB. See'node-mongodb-native' for details.

Update Operators

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." %}

Handling ObjectId

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." %}

  • NoObjectId coercion: CRUD operations can be operated with non-ObjectId-likestring or ObjectId-like string ids.

  • EnforceObjectId 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.

Model scope

This scope would do the conversion for all properties in the model.

@model({settings:{strictObjectIDCoercion:true}})exportclassUserextendsEntity{@property({type:'string',id:true,})id:string;...}

Property scope

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;}

Customize collection/field names

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." %}

Running tests

Own instance

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

Docker

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

Leak detection

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

Running benchmarks

Benchmarks must be run on a Unix-like operating system.

make benchmarks

The results will be output in./benchmarks/results.md.

Release notes

  • 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

Stars

Watchers

Forks

Packages

No packages published

Contributors73

Languages


[8]ページ先頭

©2009-2025 Movatter.jp