Skip to content

Commit 042c3ae

Browse files
committed
Deploying to gh-pages from @ f3b2933 🚀
1 parent f3b2933 commit 042c3ae

File tree

4 files changed

+0
-1226
lines changed

4 files changed

+0
-1226
lines changed
Lines changed: 0 additions & 375 deletions
Original file line numberDiff line numberDiff line change
@@ -1,375 +0,0 @@
1-
# loopback-connector-mongodb
2-
3-
The official MongoDB connector for the LoopBack framework.
4-
5-
## Installation
6-
7-
In your application root directory, enter this command to install the connector:
8-
9-
```sh
10-
npm install loopback-connector-mongodb --save
11-
```
12-
13-
This installs the module from npm and adds it as a dependency to the application's `package.json` file.
14-
15-
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 run `npm install` for you.
16-
17-
## Supported versions
18-
19-
**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.**
20-
21-
This module adopts the [Module Long Term Support (LTS)](http://github.com/CloudNativeJS/ModuleLTS) policy, with the following End Of Life (EOL) dates:
22-
23-
| Version | Status | Published | EOL | LoopBack | Juggler |
24-
| ---------- | -------------------- | --------- | -------------------- | ---------|----------|
25-
| 6.x | Current | Mar 2021 | Apr 2028 _(minimum)_ | 4 | 4.x |
26-
| 5.x | End-of-Life | Jun 2019 | Apr 2023 | 3, 4 | 3.x, 4.x |
27-
| 4.x | End-of-Life | Nov 2018 | Apr 2021 | 3, 4 | 3.x, 4.x |
28-
29-
## Creating a MongoDB data source
30-
31-
For 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.
32-
33-
After setting it up, the configuration can be found under `src/datasources/<DataSourceName>.datasource.ts`, which would look like this:
34-
35-
```ts
36-
const config = {
37-
name: 'db',
38-
connector: 'mongodb',
39-
url: '',
40-
host: 'localhost',
41-
port: 27017,
42-
user: '',
43-
password: '',
44-
database: 'testdb',
45-
};
46-
```
47-
48-
If your username or password contains special characters like `@`, `$` etc, encode the whole
49-
username or password using [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
50-
51-
Eg: `pa$$wd` would become `pa%24%24wd`.
52-
53-
### Connection properties
54-
55-
| Property | Type&nbsp;&nbsp; | Description |
56-
| ---------- | ---------------- | ---------------------------------------------------------------------------------------------------------- |
57-
| connector | String | Connector name, either `"loopback-connector-mongodb"` or `"mongodb"`. |
58-
| database | String | Database name |
59-
| host | String | Database host name |
60-
| name | String | Name of the datasource in the app |
61-
| password | String | Password to connect to database |
62-
| port | Number | Database TCP port |
63-
| url | String | Connection URL of form `mongodb://user:password@host/db`. Overrides other connection settings (see below). |
64-
| user | String | Username to connect to database |
65-
| authSource | String | Optional. Authentification database name. Usually `"admin"` value. |
66-
67-
If 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.
68-
69-
**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/).
70-
71-
### Additional properties
72-
73-
<table>
74-
<thead>
75-
<tr>
76-
<th width="160">Property</th>
77-
<th width="90">Type</th>
78-
<th>Default</th>
79-
<th>Description</th>
80-
</tr>
81-
</thead>
82-
<tbody>
83-
<tr>
84-
<td>allowExtendedOperators</td>
85-
<td>Boolean</td>
86-
<td><code>false</code></td>
87-
<td>Set to <code>true</code> to enable using MongoDB operators such as <code>$currentDate, $inc, $max, $min, $mul, $rename, $setOnInsert, $set, $unset, $addToSet, $pop, $pullAll, $pull, $push</code>, and <code>$bit</code>. See <a href="https://loopback.io/doc/en/lb4/MongoDB-connector.html#update-operators" class="external-link" rel="nofollow">Update Operators</a> section below</td>
88-
</tr>
89-
<tr>
90-
<td>enableGeoIndexing</td>
91-
<td>Boolean</td>
92-
<td><code>false</code></td>
93-
<td>Set to <code>true</code> to enable 2d sphere indexing for model properties of type <code>GeoPoint</code>. This allows for indexed <code>near</code> queries.</td>
94-
</tr>
95-
<tr>
96-
<td>lazyConnect</td>
97-
<td>Boolean</td>
98-
<td><code>false</code></td>
99-
<td>When set to <code>true</code>, 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.</td>
100-
</tr>
101-
<tr>
102-
<td>disableDefaultSort</td>
103-
<td>Boolean</td>
104-
<td><code>false</code></td>
105-
<td>Set to <code>true</code> to disable the default sorting behavior on <code>id</code> column, this will help performance using indexed columns available in MongoDB.</td>
106-
</tr>
107-
<tr>
108-
<td>collation</td>
109-
<td>String</td>
110-
<td>N/A</td>
111-
<td>Specify language-specific rules for string comparison, such as rules for letter-case and accent marks. See <a href="https://docs.mongodb.com/manual/reference/collation/">MongoDB documentation</a> for details. It can also be used to create <a href="https://docs.mongodb.com/manual/core/index-case-insensitive/">case insensitive indexes</a>.</td>
112-
</tr>
113-
</tbody>
114-
</table>
115-
116-
### Setting the url property in datasource.ts
117-
118-
You can set the `url` property to a connection URL in `<datasourceName>.datasources.ts` to override individual connection parameters such as `host`, `user`, and `password`. E.g `loopback:pa55w0rd@localhost:27017/testdb`.
119-
120-
### Using the mongodb+srv protocol
121-
122-
MongoDB supports a protocol called `mongodb+srv` for connecting to replica sets without having to give the hostname of every server in the replica set.
123-
To use `mongodb+srv` as the protocol set the `protocol` connection property in the datasource.json to `mongodb+srv`. For example:
124-
125-
```ts
126-
const config = {
127-
name: 'db',
128-
connector: 'mongodb',
129-
host: 'myserver',
130-
database: 'testdb',
131-
protocol: 'mongodb+srv',
132-
};
133-
```
134-
135-
Note: the port is not specified when using the `mongodb+srv` protocol and will be ignored if given.
136-
137-
### TLS/SSL Connections
138-
139-
Note: SSL options deprecated since MongoDB 4.2
140-
141-
```ts
142-
const config = {
143-
name: 'db',
144-
connector: 'mongodb',
145-
url: '',
146-
host: 'localhost',
147-
port: 27017,
148-
user: '',
149-
password: '',
150-
database: 'testdb',
151-
tls: true,
152-
tlsCertificateKeyFile: '/local/path/to/pem-file',
153-
tlsCAFile: '/local/path/to/ca-file',
154-
};
155-
```
156-
157-
## Security Considerations
158-
159-
MongoDB 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.
160-
161-
To 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`.
162-
163-
**Example:**
164-
165-
```ts
166-
await PostRepository.find(
167-
{ where: { $where: "function() { /*JS function here*/}" } },
168-
{ disableSanitization: true }
169-
);
170-
```
171-
172-
## Type mappings
173-
174-
See [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.
175-
176-
### LoopBack to MongoDB types
177-
178-
Type conversion is mainly handled by MongoDB. See ['node-mongodb-native'](http://mongodb.github.io/node-mongodb-native/) for details.
179-
180-
## Update Operators
181-
182-
Except 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.
183-
184-
Here is an example of updating the price for all the products under category `furniture` if their current price is lower than 100:
185-
186-
```
187-
await productRepo.updateAll({ $max: { price: 100 }}, { category: {eq: 'furniture'} // where clause goes in here });
188-
```
189-
190-
{% include tip.html content="you **will not** need the dollar sign `'$'` for operators in the Where
191-
clause." %}
192-
193-
## Handling ObjectId
194-
195-
MongoDB uses `ObjectId` for its primary key, which is an object instead of a
196-
string. In queries, string values must be cast to `ObjectId`, otherwise they are
197-
not considered as the same value. Therefore, you might want to specify the data
198-
type of properties to enforce `ObjectId` coercion. Such coercion would make sure
199-
the property value converts from ObjectId-like string to `ObjectId` when it
200-
accesses to the database and converts `ObjectId` to ObjectId-like string when
201-
the 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}\$/.)
202-
203-
LoopBack provides two scopes to handle such coercion: per model or per property. Please check the following to see which configuration meets your requirements.
204-
205-
{% include important.html content="please make sure you are using `loopback-connector-mongodb` package version 5.2.1
206-
or above to handle `ObjectId` properly." %}
207-
208-
- No `ObjectId` coercion: CRUD operations can be operated with non-ObjectId-like
209-
string or ObjectId-like string ids.
210-
211-
- Enforce `ObjectId` coercion: the property value can only be `ObjectId` or
212-
ObjectId-like string, otherwise it will be rejected.
213-
214-
Enforcing `ObjectId` coercion can be done by setting the flag
215-
`strictObjectIDCoercion` in the **model definition** or by specifying
216-
`dataType: ObjecId` in the **property definition**.
217-
218-
### Model scope
219-
220-
This scope would do the conversion for all properties in the model.
221-
222-
```ts
223-
@model({settings: {
224-
strictObjectIDCoercion: true
225-
}})
226-
export class User extends Entity {
227-
@property({
228-
type: 'string',
229-
id: true,
230-
})
231-
id: string;
232-
...
233-
}
234-
```
235-
236-
### Property scope
237-
238-
This scope would only convert an ObjectId-like string to `ObjectId` with a certain property in the model.
239-
240-
```ts
241-
@property({
242-
type: 'string',
243-
id: true,
244-
mongodb: {dataType: 'ObjectId'}
245-
}
246-
id: string;
247-
```
248-
249-
Also notice that for RELATIONS, if the primary key/source key has set to enforce ObjectId coercion
250-
(no matter by `strictObjectIDCoercion: true` or `dataType: 'ObjectId'`). The corresponding foreign key will need to have it
251-
set as well to make sure relations work smoothly.
252-
253-
```ts
254-
@model()
255-
export class User extends Entity {
256-
// source key
257-
@property({
258-
type: 'string',
259-
id: true,
260-
mongodb: {dataType: 'ObjectId'}
261-
})
262-
id: string;
263-
...
264-
}
265-
266-
@model(// )
267-
export class Address extends Entity {
268-
...
269-
// foreign key
270-
@belongsTo(() => User,
271-
{}, //relation metadata goes in here
272-
{// property definition goes in here
273-
mongodb: {dataType: 'ObjectId'}
274-
})
275-
UserId: string;
276-
}
277-
```
278-
279-
## Customize collection/field names
280-
281-
`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:{ <field>: <customValue>}`. 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:
282-
283-
{% include code-caption.html content="/src/models/User.model.ts" %}
284-
285-
```ts
286-
@model({
287-
settings: {
288-
// model definition goes in here
289-
mongodb: { collection: "Custom_Collection_User" },
290-
},
291-
})
292-
export class User extends Entity {
293-
@property({
294-
type: "string",
295-
id: true,
296-
generated: true,
297-
})
298-
id: string;
299-
300-
@property({
301-
type: "string",
302-
mongodb: {
303-
fieldName: "Custom_Name",
304-
},
305-
})
306-
name?: string;
307-
}
308-
```
309-
310-
{% 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." %}
311-
312-
## Running tests
313-
314-
### Own instance
315-
316-
If you have a local or remote MongoDB instance and would like to use that to run the test suite, use the following command:
317-
318-
- Linux
319-
320-
```bash
321-
MONGODB_HOST=<HOST> MONGODB_PORT=<PORT> MONGODB_DATABASE=<DATABASE> CI=true npm test
322-
```
323-
324-
- Windows
325-
326-
```bash
327-
SET MONGODB_HOST=<HOST> SET MONGODB_PORT=<PORT> SET MONGODB_DATABASE=<DATABASE> SET CI=true npm test
328-
```
329-
330-
### Docker
331-
332-
If you do not have a local MongoDB instance, you can also run the test suite with very minimal requirements.
333-
334-
- Assuming you have [Docker](https://docs.docker.com/engine/installation/) installed, run the following script which would spawn a MongoDB instance on your local:
335-
336-
```bash
337-
source setup.sh <HOST> <PORT> <DATABASE>
338-
```
339-
340-
where `<HOST>`, `<PORT>` and `<DATABASE>` are optional parameters. The default values are `localhost`, `27017` and `testdb` respectively.
341-
342-
- Run the test:
343-
344-
```bash
345-
npm test
346-
```
347-
348-
### Leak detection
349-
350-
Tests run for 100 iterations by default, but can be increased by setting the
351-
env var `ITERATIONS`.
352-
353-
```
354-
make leak-detection # run 100 iterations (default)
355-
```
356-
357-
or
358-
359-
```
360-
ITERATIONS=1000 make leak-detection # run 1000 iterations
361-
```
362-
363-
## Running benchmarks
364-
365-
**Benchmarks must be run on a Unix-like operating system.**
366-
367-
```
368-
make benchmarks
369-
```
370-
371-
The results will be output in `./benchmarks/results.md`.
372-
373-
## Release notes
374-
375-
- 1.1.7 - Do not return MongoDB-specific `_id` to client API, except if specifically specified in the model definition

0 commit comments

Comments
 (0)