mirror of
https://github.com/bvanroll/yahoo-thing.git
synced 2025-08-29 12:02:48 +00:00
euh
This commit is contained in:
2226
node_modules/mongodb/HISTORY.md
generated
vendored
Normal file
2226
node_modules/mongodb/HISTORY.md
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
201
node_modules/mongodb/LICENSE.md
generated
vendored
Normal file
201
node_modules/mongodb/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
493
node_modules/mongodb/README.md
generated
vendored
Normal file
493
node_modules/mongodb/README.md
generated
vendored
Normal file
@@ -0,0 +1,493 @@
|
||||
[](https://nodei.co/npm/mongodb/) [](https://nodei.co/npm/mongodb/)
|
||||
|
||||
[](http://travis-ci.org/mongodb/node-mongodb-native)
|
||||
[](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1)
|
||||
[](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
# Description
|
||||
|
||||
The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users.
|
||||
|
||||
**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).**
|
||||
|
||||
## MongoDB Node.JS Driver
|
||||
|
||||
| what | where |
|
||||
|---------------|------------------------------------------------|
|
||||
| documentation | http://mongodb.github.io/node-mongodb-native |
|
||||
| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api |
|
||||
| source | https://github.com/mongodb/node-mongodb-native |
|
||||
| mongodb | http://www.mongodb.org |
|
||||
|
||||
### Bugs / Feature Requests
|
||||
|
||||
Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
|
||||
case in our issue management tool, JIRA:
|
||||
|
||||
- Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
|
||||
- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
|
||||
- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
|
||||
|
||||
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
|
||||
Core Server (i.e. SERVER) project are **public**.
|
||||
|
||||
### Questions and Bug Reports
|
||||
|
||||
* Mailing List: [groups.google.com/forum/#!forum/node-mongodb-native](https://groups.google.com/forum/#!forum/node-mongodb-native)
|
||||
* JIRA: [jira.mongodb.org](http://jira.mongodb.org)
|
||||
|
||||
### Change Log
|
||||
|
||||
Change history can be found in [`HISTORY.md`](HISTORY.md).
|
||||
|
||||
# Installation
|
||||
|
||||
The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project.
|
||||
|
||||
## MongoDB Driver
|
||||
|
||||
Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command.
|
||||
|
||||
```bash
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
This will download the MongoDB driver and add a dependency entry in your `package.json` file.
|
||||
|
||||
You can also use the [Yarn](https://yarnpkg.com/en) package manager.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
The MongoDB driver depends on several other packages. These are:
|
||||
|
||||
* [mongodb-core](https://github.com/mongodb-js/mongodb-core)
|
||||
* [bson](https://github.com/mongodb/js-bson)
|
||||
* [kerberos](https://github.com/mongodb-js/kerberos)
|
||||
* [node-gyp](https://github.com/nodejs/node-gyp)
|
||||
|
||||
The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.
|
||||
|
||||
**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.**
|
||||
|
||||
### Diagnosing on UNIX
|
||||
|
||||
If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/mongodb-js/kerberos
|
||||
cd kerberos
|
||||
npm install
|
||||
```
|
||||
|
||||
If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally:
|
||||
|
||||
```bash
|
||||
npm install -g node-gyp
|
||||
```
|
||||
|
||||
If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command.
|
||||
|
||||
```bash
|
||||
cd yourproject
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
|
||||
|
||||
```bash
|
||||
npm --loglevel verbose install mongodb
|
||||
```
|
||||
|
||||
This will print out all the steps npm is performing while trying to install the module.
|
||||
|
||||
### Diagnosing on Windows
|
||||
|
||||
A compiler tool chain known to work for compiling `kerberos` on Windows is the following.
|
||||
|
||||
* Visual Studio C++ 2010 (do not use higher versions)
|
||||
* Windows 7 64bit SDK
|
||||
* Python 2.7 or higher
|
||||
|
||||
Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`.
|
||||
|
||||
```bash
|
||||
npm install -g node-gyp
|
||||
```
|
||||
|
||||
Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/christkv/kerberos.git
|
||||
cd kerberos
|
||||
npm install
|
||||
node-gyp rebuild
|
||||
```
|
||||
|
||||
This should rebuild the driver successfully if you have everything set up correctly.
|
||||
|
||||
### Other possible issues
|
||||
|
||||
Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).
|
||||
|
||||
Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
|
||||
|
||||
## Quick Start
|
||||
|
||||
This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md).
|
||||
|
||||
### Create the `package.json` file
|
||||
|
||||
First, create a directory where your application will live.
|
||||
|
||||
```bash
|
||||
mkdir myproject
|
||||
cd myproject
|
||||
```
|
||||
|
||||
Enter the following command and answer the questions to create the initial structure for your new project:
|
||||
|
||||
```bash
|
||||
npm init
|
||||
```
|
||||
|
||||
Next, install the driver dependency.
|
||||
|
||||
```bash
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory.
|
||||
|
||||
### Start a MongoDB Server
|
||||
|
||||
For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
|
||||
|
||||
1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
|
||||
2. Create a database directory (in this case under **/data**).
|
||||
3. Install and start a ``mongod`` process.
|
||||
|
||||
```bash
|
||||
mongod --dbpath=/data
|
||||
```
|
||||
|
||||
You should see the **mongod** process start up and print some status information.
|
||||
|
||||
### Connect to MongoDB
|
||||
|
||||
Create a new **app.js** file and add the following code to try out some basic CRUD
|
||||
operations using the MongoDB driver.
|
||||
|
||||
Add code to connect to the server and the database **myproject**:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
client.close();
|
||||
});
|
||||
```
|
||||
|
||||
Run your app from the command line with:
|
||||
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
|
||||
The application should print **Connected successfully to server** to the console.
|
||||
|
||||
### Insert a Document
|
||||
|
||||
Add to **app.js** the following function which uses the **insertMany**
|
||||
method to add three documents to the **documents** collection.
|
||||
|
||||
```js
|
||||
const insertDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Insert some documents
|
||||
collection.insertMany([
|
||||
{a : 1}, {a : 2}, {a : 3}
|
||||
], function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(3, result.result.n);
|
||||
assert.equal(3, result.ops.length);
|
||||
console.log("Inserted 3 documents into the collection");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The **insert** command returns an object with the following fields:
|
||||
|
||||
* **result** Contains the result document from MongoDB
|
||||
* **ops** Contains the documents inserted with added **_id** fields
|
||||
* **connection** Contains the connection used to perform the insert
|
||||
|
||||
Add the following code to call the **insertDocuments** function:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Run the updated **app.js** file:
|
||||
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
|
||||
The operation returns the following output:
|
||||
|
||||
```bash
|
||||
Connected successfully to server
|
||||
Inserted 3 documents into the collection
|
||||
```
|
||||
|
||||
### Find All Documents
|
||||
|
||||
Add a query that returns all the documents.
|
||||
|
||||
```js
|
||||
const findDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Find some documents
|
||||
collection.find({}).toArray(function(err, docs) {
|
||||
assert.equal(err, null);
|
||||
console.log("Found the following records");
|
||||
console.log(docs)
|
||||
callback(docs);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected correctly to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
findDocuments(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Find Documents with a Query Filter
|
||||
|
||||
Add a query filter to find only documents which meet the query criteria.
|
||||
|
||||
```js
|
||||
const findDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Find some documents
|
||||
collection.find({'a': 3}).toArray(function(err, docs) {
|
||||
assert.equal(err, null);
|
||||
console.log("Found the following records");
|
||||
console.log(docs);
|
||||
callback(docs);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Only the documents which match ``'a' : 3`` should be returned.
|
||||
|
||||
### Update a document
|
||||
|
||||
The following operation updates a document in the **documents** collection.
|
||||
|
||||
```js
|
||||
const updateDocument = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Update document where a is 2, set b equal to 1
|
||||
collection.updateOne({ a : 2 }
|
||||
, { $set: { b : 1 } }, function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(1, result.result.n);
|
||||
console.log("Updated the document with the field a equal to 2");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method.
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
updateDocument(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Remove a document
|
||||
|
||||
Remove the document where the field **a** is equal to **3**.
|
||||
|
||||
```js
|
||||
const removeDocument = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Delete document where a is 3
|
||||
collection.deleteOne({ a : 3 }, function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(1, result.result.n);
|
||||
console.log("Removed the document with the field a equal to 3");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Add the new method to the **MongoClient.connect** callback function.
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
updateDocument(db, function() {
|
||||
removeDocument(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Index a Collection
|
||||
|
||||
[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
|
||||
performance. The following function creates an index on the **a** field in the
|
||||
**documents** collection.
|
||||
|
||||
```js
|
||||
const indexCollection = function(db, callback) {
|
||||
db.collection('documents').createIndex(
|
||||
{ "a": 1 },
|
||||
null,
|
||||
function(err, results) {
|
||||
console.log(results);
|
||||
callback();
|
||||
}
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
Add the ``indexCollection`` method to your app:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
indexCollection(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md).
|
||||
|
||||
## Next Steps
|
||||
|
||||
* [MongoDB Documentation](http://mongodb.org)
|
||||
* [Read about Schemas](http://learnmongodbthehardway.com)
|
||||
* [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE.md)
|
||||
|
||||
© 2009-2012 Christian Amor Kvalheim
|
||||
© 2012-present MongoDB [Contributors](CONTRIBUTORS.md)
|
67
node_modules/mongodb/index.js
generated
vendored
Normal file
67
node_modules/mongodb/index.js
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
// Core module
|
||||
const core = require('mongodb-core');
|
||||
const Instrumentation = require('./lib/apm');
|
||||
|
||||
// Set up the connect function
|
||||
const connect = require('./lib/mongo_client').connect;
|
||||
|
||||
// Expose error class
|
||||
connect.MongoError = core.MongoError;
|
||||
connect.MongoNetworkError = core.MongoNetworkError;
|
||||
|
||||
// Actual driver classes exported
|
||||
connect.Admin = require('./lib/admin');
|
||||
connect.MongoClient = require('./lib/mongo_client');
|
||||
connect.Db = require('./lib/db');
|
||||
connect.Collection = require('./lib/collection');
|
||||
connect.Server = require('./lib/topologies/server');
|
||||
connect.ReplSet = require('./lib/topologies/replset');
|
||||
connect.Mongos = require('./lib/topologies/mongos');
|
||||
connect.ReadPreference = require('mongodb-core').ReadPreference;
|
||||
connect.GridStore = require('./lib/gridfs/grid_store');
|
||||
connect.Chunk = require('./lib/gridfs/chunk');
|
||||
connect.Logger = core.Logger;
|
||||
connect.AggregationCursor = require('./lib/aggregation_cursor');
|
||||
connect.CommandCursor = require('./lib/command_cursor');
|
||||
connect.Cursor = require('./lib/cursor');
|
||||
connect.GridFSBucket = require('./lib/gridfs-stream');
|
||||
// Exported to be used in tests not to be used anywhere else
|
||||
connect.CoreServer = require('mongodb-core').Server;
|
||||
connect.CoreConnection = require('mongodb-core').Connection;
|
||||
|
||||
// BSON types exported
|
||||
connect.Binary = core.BSON.Binary;
|
||||
connect.Code = core.BSON.Code;
|
||||
connect.Map = core.BSON.Map;
|
||||
connect.DBRef = core.BSON.DBRef;
|
||||
connect.Double = core.BSON.Double;
|
||||
connect.Int32 = core.BSON.Int32;
|
||||
connect.Long = core.BSON.Long;
|
||||
connect.MinKey = core.BSON.MinKey;
|
||||
connect.MaxKey = core.BSON.MaxKey;
|
||||
connect.ObjectID = core.BSON.ObjectID;
|
||||
connect.ObjectId = core.BSON.ObjectID;
|
||||
connect.Symbol = core.BSON.Symbol;
|
||||
connect.Timestamp = core.BSON.Timestamp;
|
||||
connect.BSONRegExp = core.BSON.BSONRegExp;
|
||||
connect.Decimal128 = core.BSON.Decimal128;
|
||||
|
||||
// Add connect method
|
||||
connect.connect = connect;
|
||||
|
||||
// Set up the instrumentation method
|
||||
connect.instrument = function(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
const instrumentation = new Instrumentation();
|
||||
instrumentation.instrument(connect.MongoClient, callback);
|
||||
return instrumentation;
|
||||
};
|
||||
|
||||
// Set our exports to be the connect function
|
||||
module.exports = connect;
|
293
node_modules/mongodb/lib/admin.js
generated
vendored
Normal file
293
node_modules/mongodb/lib/admin.js
generated
vendored
Normal file
@@ -0,0 +1,293 @@
|
||||
'use strict';
|
||||
|
||||
const executeOperation = require('./utils').executeOperation;
|
||||
const applyWriteConcern = require('./utils').applyWriteConcern;
|
||||
|
||||
const addUser = require('./operations/db_ops').addUser;
|
||||
const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand;
|
||||
const removeUser = require('./operations/db_ops').removeUser;
|
||||
const replSetGetStatus = require('./operations/admin_ops').replSetGetStatus;
|
||||
const serverStatus = require('./operations/admin_ops').serverStatus;
|
||||
const validateCollection = require('./operations/admin_ops').validateCollection;
|
||||
|
||||
/**
|
||||
* @fileOverview The **Admin** class is an internal class that allows convenient access to
|
||||
* the admin functionality and commands for MongoDB.
|
||||
*
|
||||
* **ADMIN Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
*
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Use the admin database for the operation
|
||||
* const adminDb = client.db(dbName).admin();
|
||||
*
|
||||
* // List all the available databases
|
||||
* adminDb.listDatabases(function(err, dbs) {
|
||||
* test.equal(null, err);
|
||||
* test.ok(dbs.databases.length > 0);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @return {Admin} a collection instance.
|
||||
*/
|
||||
function Admin(db, topology, promiseLibrary) {
|
||||
if (!(this instanceof Admin)) return new Admin(db, topology);
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
db: db,
|
||||
topology: topology,
|
||||
promiseLibrary: promiseLibrary
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback Admin~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
* @method
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.command = function(command, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [
|
||||
this.s.db,
|
||||
command,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.buildInfo = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { buildinfo: 1 };
|
||||
return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [
|
||||
this.s.db,
|
||||
cmd,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.serverInfo = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { buildinfo: 1 };
|
||||
return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [
|
||||
this.s.db,
|
||||
cmd,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve this db's server status.
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.serverStatus = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Ping the MongoDB server and retrieve results
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.ping = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { ping: 1 };
|
||||
return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [
|
||||
this.s.db,
|
||||
cmd,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a user to the database.
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {string} password The password.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)
|
||||
* @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.addUser = function(username, password, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 2);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
|
||||
options = args.length ? args.shift() : {};
|
||||
options = Object.assign({}, options);
|
||||
// Get the options
|
||||
options = applyWriteConcern(options, { db: this.s.db });
|
||||
// Set the db name to admin
|
||||
options.dbName = 'admin';
|
||||
|
||||
return executeOperation(this.s.db.s.topology, addUser, [
|
||||
this.s.db,
|
||||
username,
|
||||
password,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove a user from a database
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.removeUser = function(username, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
|
||||
options = args.length ? args.shift() : {};
|
||||
options = Object.assign({}, options);
|
||||
// Get the options
|
||||
options = applyWriteConcern(options, { db: this.s.db });
|
||||
// Set the db name
|
||||
options.dbName = 'admin';
|
||||
|
||||
return executeOperation(this.s.db.s.topology, removeUser, [
|
||||
this.s.db,
|
||||
username,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate an existing collection
|
||||
*
|
||||
* @param {string} collectionName The name of the collection to validate.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.validateCollection = function(collectionName, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.db.s.topology, validateCollection, [
|
||||
this,
|
||||
collectionName,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* List the available databases
|
||||
*
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.listDatabases = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { listDatabases: 1 };
|
||||
if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly);
|
||||
return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [
|
||||
this.s.db,
|
||||
cmd,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get ReplicaSet status
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.replSetGetStatus = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]);
|
||||
};
|
||||
|
||||
module.exports = Admin;
|
407
node_modules/mongodb/lib/aggregation_cursor.js
generated
vendored
Normal file
407
node_modules/mongodb/lib/aggregation_cursor.js
generated
vendored
Normal file
@@ -0,0 +1,407 @@
|
||||
'use strict';
|
||||
|
||||
const inherits = require('util').inherits;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const Readable = require('stream').Readable;
|
||||
const CoreCursor = require('./cursor');
|
||||
|
||||
/**
|
||||
* @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
|
||||
* allowing for iteration over the results returned from the underlying query. It supports
|
||||
* one by one document iteration, conversion to an array or can be iterated as a Node 4.X
|
||||
* or higher stream
|
||||
*
|
||||
* **AGGREGATIONCURSOR Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Create a collection we want to drop later
|
||||
* const col = client.db(dbName).collection('createIndexExample1');
|
||||
* // Insert a bunch of documents
|
||||
* col.insert([{a:1, b:1}
|
||||
* , {a:2, b:2}, {a:3, b:3}
|
||||
* , {a:4, b:4}], {w:1}, function(err, result) {
|
||||
* test.equal(null, err);
|
||||
* // Show that duplicate records got dropped
|
||||
* col.aggregation({}, {cursor: {}}).toArray(function(err, items) {
|
||||
* test.equal(null, err);
|
||||
* test.equal(4, items.length);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Namespace provided by the browser.
|
||||
* @external Readable
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class AggregationCursor
|
||||
* @extends external:Readable
|
||||
* @fires AggregationCursor#data
|
||||
* @fires AggregationCursor#end
|
||||
* @fires AggregationCursor#close
|
||||
* @fires AggregationCursor#readable
|
||||
* @return {AggregationCursor} an AggregationCursor instance.
|
||||
*/
|
||||
var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
|
||||
CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
|
||||
var state = AggregationCursor.INIT;
|
||||
var streamOptions = {};
|
||||
|
||||
// MaxTimeMS
|
||||
var maxTimeMS = null;
|
||||
|
||||
// Get the promiseLibrary
|
||||
var promiseLibrary = options.promiseLibrary || Promise;
|
||||
|
||||
// Set up
|
||||
Readable.call(this, { objectMode: true });
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
// MaxTimeMS
|
||||
maxTimeMS: maxTimeMS,
|
||||
// State
|
||||
state: state,
|
||||
// Stream options
|
||||
streamOptions: streamOptions,
|
||||
// BSON
|
||||
bson: bson,
|
||||
// Namespace
|
||||
ns: ns,
|
||||
// Command
|
||||
cmd: cmd,
|
||||
// Options
|
||||
options: options,
|
||||
// Topology
|
||||
topology: topology,
|
||||
// Topology Options
|
||||
topologyOptions: topologyOptions,
|
||||
// Promise library
|
||||
promiseLibrary: promiseLibrary,
|
||||
// Optional ClientSession
|
||||
session: options.session
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* AggregationCursor stream data event, fired for each document in the cursor.
|
||||
*
|
||||
* @event AggregationCursor#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream end event
|
||||
*
|
||||
* @event AggregationCursor#end
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream close event
|
||||
*
|
||||
* @event AggregationCursor#close
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream readable event
|
||||
*
|
||||
* @event AggregationCursor#readable
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
// Inherit from Readable
|
||||
inherits(AggregationCursor, Readable);
|
||||
|
||||
// Extend the Cursor
|
||||
for (var name in CoreCursor.prototype) {
|
||||
AggregationCursor.prototype[name] = CoreCursor.prototype[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the batch size for the cursor.
|
||||
* @method
|
||||
* @param {number} value The batchSize for the cursor.
|
||||
* @throws {MongoError}
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.batchSize = function(value) {
|
||||
if (this.s.state === AggregationCursor.CLOSED || this.isDead())
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
if (typeof value !== 'number')
|
||||
throw MongoError.create({ message: 'batchSize requires an integer', drvier: true });
|
||||
if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
|
||||
this.setCursorBatchSize(value);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a geoNear stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The geoNear stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.geoNear = function(document) {
|
||||
this.s.cmd.pipeline.push({ $geoNear: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a group stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The group stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.group = function(document) {
|
||||
this.s.cmd.pipeline.push({ $group: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a limit stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state limit value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.limit = function(value) {
|
||||
this.s.cmd.pipeline.push({ $limit: value });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a match stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The match stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.match = function(document) {
|
||||
this.s.cmd.pipeline.push({ $match: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a maxTimeMS stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state maxTimeMS value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.maxTimeMS = function(value) {
|
||||
if (this.s.topology.lastIsMaster().minWireVersion > 2) {
|
||||
this.s.cmd.maxTimeMS = value;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a out stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} destination The destination name.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.out = function(destination) {
|
||||
this.s.cmd.pipeline.push({ $out: destination });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a project stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The project stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.project = function(document) {
|
||||
this.s.cmd.pipeline.push({ $project: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a lookup stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The lookup stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.lookup = function(document) {
|
||||
this.s.cmd.pipeline.push({ $lookup: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a redact stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The redact stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.redact = function(document) {
|
||||
this.s.cmd.pipeline.push({ $redact: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a skip stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state skip value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.skip = function(value) {
|
||||
this.s.cmd.pipeline.push({ $skip: value });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a sort stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The sort stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.sort = function(document) {
|
||||
this.s.cmd.pipeline.push({ $sort: document });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a unwind stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} field The unwind field name.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
AggregationCursor.prototype.unwind = function(field) {
|
||||
this.s.cmd.pipeline.push({ $unwind: field });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the cursor logger
|
||||
* @method
|
||||
* @return {Logger} return the cursor logger
|
||||
* @ignore
|
||||
*/
|
||||
AggregationCursor.prototype.getLogger = function() {
|
||||
return this.logger;
|
||||
};
|
||||
|
||||
AggregationCursor.prototype.get = AggregationCursor.prototype.toArray;
|
||||
|
||||
/**
|
||||
* Get the next available document from the cursor, returns null if no more documents are available.
|
||||
* @function AggregationCursor.prototype.next
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the cursor
|
||||
* @function AggregationCursor.prototype.hasNext
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback AggregationCursor~toArrayResultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object[]} documents All the documents the satisfy the cursor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns an array of documents. The caller is responsible for making sure that there
|
||||
* is enough memory to store the results. Note that the array only contain partial
|
||||
* results when this cursor had been previouly accessed. In that case,
|
||||
* cursor.rewind() can be used to reset the cursor.
|
||||
* @method AggregationCursor.prototype.toArray
|
||||
* @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback AggregationCursor~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
|
||||
* not all of the elements will be iterated if this cursor had been previouly accessed.
|
||||
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
|
||||
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
|
||||
* at any given time if batch size is specified. Otherwise, the caller is responsible
|
||||
* for making sure that the entire result can fit the memory.
|
||||
* @method AggregationCursor.prototype.each
|
||||
* @param {AggregationCursor~resultCallback} callback The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Close the cursor, sending a AggregationCursor command and emitting close.
|
||||
* @method AggregationCursor.prototype.close
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Is the cursor closed
|
||||
* @method AggregationCursor.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute the explain for the cursor
|
||||
* @method AggregationCursor.prototype.explain
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clone the cursor
|
||||
* @function AggregationCursor.prototype.clone
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resets the cursor
|
||||
* @function AggregationCursor.prototype.rewind
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for the forEach iterator method
|
||||
* @callback AggregationCursor~iteratorCallback
|
||||
* @param {Object} doc An emitted document for the iterator
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback error format for the forEach iterator method
|
||||
* @callback AggregationCursor~endCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Iterates over all the documents for this cursor using the iterator, callback pattern.
|
||||
* @method AggregationCursor.prototype.forEach
|
||||
* @param {AggregationCursor~iteratorCallback} iterator The iteration callback.
|
||||
* @param {AggregationCursor~endCallback} callback The end callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
AggregationCursor.INIT = 0;
|
||||
AggregationCursor.OPEN = 1;
|
||||
AggregationCursor.CLOSED = 2;
|
||||
|
||||
module.exports = AggregationCursor;
|
31
node_modules/mongodb/lib/apm.js
generated
vendored
Normal file
31
node_modules/mongodb/lib/apm.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
|
||||
class Instrumentation extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
instrument(MongoClient, callback) {
|
||||
// store a reference to the original functions
|
||||
this.$MongoClient = MongoClient;
|
||||
const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect);
|
||||
|
||||
const instrumentation = this;
|
||||
MongoClient.prototype.connect = function(callback) {
|
||||
this.s.options.monitorCommands = true;
|
||||
this.on('commandStarted', event => instrumentation.emit('started', event));
|
||||
this.on('commandSucceeded', event => instrumentation.emit('succeeded', event));
|
||||
this.on('commandFailed', event => instrumentation.emit('failed', event));
|
||||
return $prototypeConnect.call(this, callback);
|
||||
};
|
||||
|
||||
if (typeof callback === 'function') callback(null, this);
|
||||
}
|
||||
|
||||
uninstrument() {
|
||||
this.$MongoClient.prototype.connect = this.$prototypeConnect;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Instrumentation;
|
136
node_modules/mongodb/lib/authenticate.js
generated
vendored
Normal file
136
node_modules/mongodb/lib/authenticate.js
generated
vendored
Normal file
@@ -0,0 +1,136 @@
|
||||
'use strict';
|
||||
|
||||
var shallowClone = require('./utils').shallowClone,
|
||||
handleCallback = require('./utils').handleCallback,
|
||||
MongoError = require('mongodb-core').MongoError,
|
||||
f = require('util').format;
|
||||
|
||||
var authenticate = function(client, username, password, options, callback) {
|
||||
// Did the user destroy the topology
|
||||
if (client.topology && client.topology.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
|
||||
// the default db to authenticate against is 'self'
|
||||
// if authententicate is called from a retry context, it may be another one, like admin
|
||||
var authdb = options.dbName;
|
||||
authdb = options.authdb ? options.authdb : authdb;
|
||||
authdb = options.authSource ? options.authSource : authdb;
|
||||
|
||||
// Callback
|
||||
var _callback = function(err, result) {
|
||||
if (client.listeners('authenticated').length > 0) {
|
||||
client.emit('authenticated', err, result);
|
||||
}
|
||||
|
||||
// Return to caller
|
||||
handleCallback(callback, err, result);
|
||||
};
|
||||
|
||||
// authMechanism
|
||||
var authMechanism = options.authMechanism || '';
|
||||
authMechanism = authMechanism.toUpperCase();
|
||||
|
||||
// If classic auth delegate to auth command
|
||||
if (authMechanism === 'MONGODB-CR') {
|
||||
client.topology.auth('mongocr', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else if (authMechanism === 'PLAIN') {
|
||||
client.topology.auth('plain', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else if (authMechanism === 'MONGODB-X509') {
|
||||
client.topology.auth('x509', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else if (authMechanism === 'SCRAM-SHA-1') {
|
||||
client.topology.auth('scram-sha-1', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else if (authMechanism === 'SCRAM-SHA-256') {
|
||||
client.topology.auth('scram-sha-256', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else if (authMechanism === 'GSSAPI') {
|
||||
if (process.platform === 'win32') {
|
||||
client.topology.auth('sspi', authdb, username, password, options, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else {
|
||||
client.topology.auth('gssapi', authdb, username, password, options, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
}
|
||||
} else if (authMechanism === 'DEFAULT') {
|
||||
client.topology.auth('default', authdb, username, password, function(err) {
|
||||
if (err) return handleCallback(callback, err, false);
|
||||
_callback(null, true);
|
||||
});
|
||||
} else {
|
||||
handleCallback(
|
||||
callback,
|
||||
MongoError.create({
|
||||
message: f('authentication mechanism %s not supported', options.authMechanism),
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function(self, username, password, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
// Shallow copy the options
|
||||
options = shallowClone(options);
|
||||
|
||||
// Set default mechanism
|
||||
if (!options.authMechanism) {
|
||||
options.authMechanism = 'DEFAULT';
|
||||
} else if (
|
||||
options.authMechanism !== 'GSSAPI' &&
|
||||
options.authMechanism !== 'DEFAULT' &&
|
||||
options.authMechanism !== 'MONGODB-CR' &&
|
||||
options.authMechanism !== 'MONGODB-X509' &&
|
||||
options.authMechanism !== 'SCRAM-SHA-1' &&
|
||||
options.authMechanism !== 'SCRAM-SHA-256' &&
|
||||
options.authMechanism !== 'PLAIN'
|
||||
) {
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({
|
||||
message:
|
||||
'only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism',
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// If we have a callback fallback
|
||||
if (typeof callback === 'function')
|
||||
return authenticate(self, username, password, options, function(err, r) {
|
||||
// Support failed auth method
|
||||
if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59;
|
||||
// Reject error
|
||||
if (err) return callback(err, r);
|
||||
callback(null, r);
|
||||
});
|
||||
|
||||
// Return a promise
|
||||
return new self.s.promiseLibrary(function(resolve, reject) {
|
||||
authenticate(self, username, password, options, function(err, r) {
|
||||
// Support failed auth method
|
||||
if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59;
|
||||
// Reject error
|
||||
if (err) return reject(err);
|
||||
resolve(r);
|
||||
});
|
||||
});
|
||||
};
|
1113
node_modules/mongodb/lib/bulk/common.js
generated
vendored
Normal file
1113
node_modules/mongodb/lib/bulk/common.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
182
node_modules/mongodb/lib/bulk/ordered.js
generated
vendored
Normal file
182
node_modules/mongodb/lib/bulk/ordered.js
generated
vendored
Normal file
@@ -0,0 +1,182 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('./common');
|
||||
const BulkOperationBase = common.BulkOperationBase;
|
||||
const utils = require('../utils');
|
||||
const toError = utils.toError;
|
||||
const handleCallback = utils.handleCallback;
|
||||
const BulkWriteResult = common.BulkWriteResult;
|
||||
const Batch = common.Batch;
|
||||
const mergeBatchResults = common.mergeBatchResults;
|
||||
const executeOperation = utils.executeOperation;
|
||||
const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError;
|
||||
const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError;
|
||||
const bson = common.bson;
|
||||
const isPromiseLike = require('../utils').isPromiseLike;
|
||||
|
||||
/**
|
||||
* Add to internal list of Operations
|
||||
*
|
||||
* @param {OrderedBulkOperation} bulkOperation
|
||||
* @param {number} docType number indicating the document type
|
||||
* @param {object} document
|
||||
* @return {OrderedBulkOperation}
|
||||
*/
|
||||
function addToOperationsList(bulkOperation, docType, document) {
|
||||
// Get the bsonSize
|
||||
const bsonSize = bson.calculateObjectSize(document, {
|
||||
checkKeys: false
|
||||
});
|
||||
|
||||
// Throw error if the doc is bigger than the max BSON size
|
||||
if (bsonSize >= bulkOperation.s.maxBatchSizeBytes)
|
||||
throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes);
|
||||
|
||||
// Create a new batch object if we don't have a current one
|
||||
if (bulkOperation.s.currentBatch == null)
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
const maxKeySize = bulkOperation.s.maxKeySize;
|
||||
|
||||
// Check if we need to create a new batch
|
||||
if (
|
||||
bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize ||
|
||||
bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >=
|
||||
bulkOperation.s.maxBatchSizeBytes ||
|
||||
bulkOperation.s.currentBatch.batchType !== docType
|
||||
) {
|
||||
// Save the batch to the execution stack
|
||||
bulkOperation.s.batches.push(bulkOperation.s.currentBatch);
|
||||
|
||||
// Create a new batch
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
// Reset the current size trackers
|
||||
bulkOperation.s.currentBatchSize = 0;
|
||||
bulkOperation.s.currentBatchSizeBytes = 0;
|
||||
}
|
||||
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.bulkResult.insertedIds.push({
|
||||
index: bulkOperation.s.currentIndex,
|
||||
_id: document._id
|
||||
});
|
||||
}
|
||||
|
||||
// We have an array of documents
|
||||
if (Array.isArray(document)) {
|
||||
throw toError('operation passed in cannot be an Array');
|
||||
}
|
||||
|
||||
bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);
|
||||
bulkOperation.s.currentBatch.operations.push(document);
|
||||
bulkOperation.s.currentBatchSize += 1;
|
||||
bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize;
|
||||
bulkOperation.s.currentIndex += 1;
|
||||
|
||||
// Return bulkOperation
|
||||
return bulkOperation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @property {number} length Get the number of operations in the bulk.
|
||||
* @return {OrderedBulkOperation} a OrderedBulkOperation instance.
|
||||
*/
|
||||
|
||||
class OrderedBulkOperation extends BulkOperationBase {
|
||||
constructor(topology, collection, options) {
|
||||
options = options || {};
|
||||
options = Object.assign(options, { addToOperationsList });
|
||||
|
||||
super(topology, collection, options, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback OrderedBulkOperation~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {BulkWriteResult} result The bulk write result.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute the ordered bulk operation
|
||||
*
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {OrderedBulkOperation~resultCallback} [callback] The result callback
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
execute(_writeConcern, options, callback) {
|
||||
const ret = this.bulkExecute(_writeConcern, options, callback);
|
||||
if (isPromiseLike(ret)) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
options = ret.options;
|
||||
callback = ret.callback;
|
||||
|
||||
return executeOperation(this.s.topology, executeCommands, [this, options, callback]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute next write command in a chain
|
||||
*
|
||||
* @param {OrderedBulkOperation} bulkOperation
|
||||
* @param {object} options
|
||||
* @param {function} callback
|
||||
*/
|
||||
function executeCommands(bulkOperation, options, callback) {
|
||||
if (bulkOperation.s.batches.length === 0) {
|
||||
return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
|
||||
}
|
||||
|
||||
// Ordered execution of the command
|
||||
const batch = bulkOperation.s.batches.shift();
|
||||
|
||||
function resultHandler(err, result) {
|
||||
// Error is a driver related error not a bulk op error, terminate
|
||||
if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
|
||||
// If we have and error
|
||||
if (err) err.ok = 0;
|
||||
if (err instanceof MongoWriteConcernError) {
|
||||
return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback);
|
||||
}
|
||||
|
||||
// Merge the results together
|
||||
const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
|
||||
const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result);
|
||||
if (mergeResult != null) {
|
||||
return handleCallback(callback, null, writeResult);
|
||||
}
|
||||
|
||||
if (bulkOperation.handleWriteError(callback, writeResult)) return;
|
||||
|
||||
// Execute the next command in line
|
||||
executeCommands(bulkOperation, options, callback);
|
||||
}
|
||||
|
||||
bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unordered batch object
|
||||
* @ignore
|
||||
*/
|
||||
function initializeOrderedBulkOp(topology, collection, options) {
|
||||
return new OrderedBulkOperation(topology, collection, options);
|
||||
}
|
||||
|
||||
initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation;
|
||||
module.exports = initializeOrderedBulkOp;
|
||||
module.exports.Bulk = OrderedBulkOperation;
|
219
node_modules/mongodb/lib/bulk/unordered.js
generated
vendored
Normal file
219
node_modules/mongodb/lib/bulk/unordered.js
generated
vendored
Normal file
@@ -0,0 +1,219 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('./common');
|
||||
const BulkOperationBase = common.BulkOperationBase;
|
||||
const utils = require('../utils');
|
||||
const toError = utils.toError;
|
||||
const handleCallback = utils.handleCallback;
|
||||
const BulkWriteResult = common.BulkWriteResult;
|
||||
const Batch = common.Batch;
|
||||
const mergeBatchResults = common.mergeBatchResults;
|
||||
const executeOperation = utils.executeOperation;
|
||||
const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError;
|
||||
const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError;
|
||||
const bson = common.bson;
|
||||
const isPromiseLike = require('../utils').isPromiseLike;
|
||||
|
||||
/**
|
||||
* Add to internal list of Operations
|
||||
*
|
||||
* @param {UnorderedBulkOperation} bulkOperation
|
||||
* @param {number} docType number indicating the document type
|
||||
* @param {object} document
|
||||
* @return {UnorderedBulkOperation}
|
||||
*/
|
||||
function addToOperationsList(bulkOperation, docType, document) {
|
||||
// Get the bsonSize
|
||||
const bsonSize = bson.calculateObjectSize(document, {
|
||||
checkKeys: false
|
||||
});
|
||||
// Throw error if the doc is bigger than the max BSON size
|
||||
if (bsonSize >= bulkOperation.s.maxBatchSizeBytes)
|
||||
throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes);
|
||||
// Holds the current batch
|
||||
bulkOperation.s.currentBatch = null;
|
||||
// Get the right type of batch
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch;
|
||||
} else if (docType === common.UPDATE) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch;
|
||||
} else if (docType === common.REMOVE) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch;
|
||||
}
|
||||
|
||||
const maxKeySize = bulkOperation.s.maxKeySize;
|
||||
|
||||
// Create a new batch object if we don't have a current one
|
||||
if (bulkOperation.s.currentBatch == null)
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
// Check if we need to create a new batch
|
||||
if (
|
||||
bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize ||
|
||||
bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >=
|
||||
bulkOperation.s.maxBatchSizeBytes ||
|
||||
bulkOperation.s.currentBatch.batchType !== docType
|
||||
) {
|
||||
// Save the batch to the execution stack
|
||||
bulkOperation.s.batches.push(bulkOperation.s.currentBatch);
|
||||
|
||||
// Create a new batch
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
}
|
||||
|
||||
// We have an array of documents
|
||||
if (Array.isArray(document)) {
|
||||
throw toError('operation passed in cannot be an Array');
|
||||
}
|
||||
|
||||
bulkOperation.s.currentBatch.operations.push(document);
|
||||
bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);
|
||||
bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1;
|
||||
|
||||
// Save back the current Batch to the right type
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch;
|
||||
bulkOperation.s.bulkResult.insertedIds.push({
|
||||
index: bulkOperation.s.bulkResult.insertedIds.length,
|
||||
_id: document._id
|
||||
});
|
||||
} else if (docType === common.UPDATE) {
|
||||
bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch;
|
||||
} else if (docType === common.REMOVE) {
|
||||
bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch;
|
||||
}
|
||||
|
||||
// Update current batch size
|
||||
bulkOperation.s.currentBatch.size += 1;
|
||||
bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize;
|
||||
|
||||
// Return bulkOperation
|
||||
return bulkOperation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @property {number} length Get the number of operations in the bulk.
|
||||
* @return {UnorderedBulkOperation} a UnorderedBulkOperation instance.
|
||||
*/
|
||||
class UnorderedBulkOperation extends BulkOperationBase {
|
||||
constructor(topology, collection, options) {
|
||||
options = options || {};
|
||||
options = Object.assign(options, { addToOperationsList });
|
||||
|
||||
super(topology, collection, options, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback UnorderedBulkOperation~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {BulkWriteResult} result The bulk write result.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute the ordered bulk operation
|
||||
*
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {UnorderedBulkOperation~resultCallback} [callback] The result callback
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
execute(_writeConcern, options, callback) {
|
||||
const ret = this.bulkExecute(_writeConcern, options, callback);
|
||||
if (isPromiseLike(ret)) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
options = ret.options;
|
||||
callback = ret.callback;
|
||||
|
||||
return executeOperation(this.s.topology, executeBatches, [this, options, callback]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the command
|
||||
*
|
||||
* @param {UnorderedBulkOperation} bulkOperation
|
||||
* @param {object} batch
|
||||
* @param {object} options
|
||||
* @param {function} callback
|
||||
*/
|
||||
function executeBatch(bulkOperation, batch, options, callback) {
|
||||
function resultHandler(err, result) {
|
||||
// Error is a driver related error not a bulk op error, terminate
|
||||
if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
|
||||
// If we have and error
|
||||
if (err) err.ok = 0;
|
||||
if (err instanceof MongoWriteConcernError) {
|
||||
return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
|
||||
}
|
||||
handleCallback(
|
||||
callback,
|
||||
null,
|
||||
mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
|
||||
);
|
||||
}
|
||||
|
||||
bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all the commands
|
||||
*
|
||||
* @param {UnorderedBulkOperation} bulkOperation
|
||||
* @param {object} options
|
||||
* @param {function} callback
|
||||
*/
|
||||
function executeBatches(bulkOperation, options, callback) {
|
||||
let numberOfCommandsToExecute = bulkOperation.s.batches.length;
|
||||
let hasErrored = false;
|
||||
// Execute over all the batches
|
||||
for (let i = 0; i < bulkOperation.s.batches.length; i++) {
|
||||
executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) {
|
||||
if (hasErrored) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (err) {
|
||||
hasErrored = true;
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
// Count down the number of commands left to execute
|
||||
numberOfCommandsToExecute = numberOfCommandsToExecute - 1;
|
||||
|
||||
// Execute
|
||||
if (numberOfCommandsToExecute === 0) {
|
||||
// Driver level error
|
||||
if (err) return handleCallback(callback, err);
|
||||
|
||||
const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
|
||||
if (bulkOperation.handleWriteError(callback, writeResult)) return;
|
||||
|
||||
return handleCallback(callback, null, writeResult);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unordered batch object
|
||||
* @ignore
|
||||
*/
|
||||
function initializeUnorderedBulkOp(topology, collection, options) {
|
||||
return new UnorderedBulkOperation(topology, collection, options);
|
||||
}
|
||||
|
||||
initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation;
|
||||
module.exports = initializeUnorderedBulkOp;
|
||||
module.exports.Bulk = UnorderedBulkOperation;
|
469
node_modules/mongodb/lib/change_stream.js
generated
vendored
Normal file
469
node_modules/mongodb/lib/change_stream.js
generated
vendored
Normal file
@@ -0,0 +1,469 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events');
|
||||
const isResumableError = require('./error').isResumableError;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
|
||||
var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference'];
|
||||
|
||||
const CHANGE_DOMAIN_TYPES = {
|
||||
COLLECTION: Symbol('Collection'),
|
||||
DATABASE: Symbol('Database'),
|
||||
CLUSTER: Symbol('Cluster')
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
|
||||
* @class ChangeStream
|
||||
* @since 3.0.0
|
||||
* @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream
|
||||
* @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
|
||||
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
|
||||
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
|
||||
* @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
|
||||
* @fires ChangeStream#close
|
||||
* @fires ChangeStream#change
|
||||
* @fires ChangeStream#end
|
||||
* @fires ChangeStream#error
|
||||
* @return {ChangeStream} a ChangeStream instance.
|
||||
*/
|
||||
|
||||
class ChangeStream extends EventEmitter {
|
||||
constructor(changeDomain, pipeline, options) {
|
||||
super();
|
||||
const Collection = require('./collection');
|
||||
const Db = require('./db');
|
||||
const MongoClient = require('./mongo_client');
|
||||
|
||||
this.pipeline = pipeline || [];
|
||||
this.options = options || {};
|
||||
this.cursorNamespace = undefined;
|
||||
this.namespace = {};
|
||||
|
||||
if (changeDomain instanceof Collection) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.COLLECTION;
|
||||
this.topology = changeDomain.s.db.serverConfig;
|
||||
|
||||
this.namespace = {
|
||||
collection: changeDomain.collectionName,
|
||||
database: changeDomain.s.db.databaseName
|
||||
};
|
||||
|
||||
this.cursorNamespace = `${this.namespace.database}.${this.namespace.collection}`;
|
||||
} else if (changeDomain instanceof Db) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.DATABASE;
|
||||
this.namespace = { collection: '', database: changeDomain.databaseName };
|
||||
this.cursorNamespace = this.namespace.database;
|
||||
this.topology = changeDomain.serverConfig;
|
||||
} else if (changeDomain instanceof MongoClient) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.CLUSTER;
|
||||
this.namespace = { collection: '', database: 'admin' };
|
||||
this.cursorNamespace = this.namespace.database;
|
||||
this.topology = changeDomain.topology;
|
||||
} else {
|
||||
throw new TypeError(
|
||||
'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient'
|
||||
);
|
||||
}
|
||||
|
||||
this.promiseLibrary = changeDomain.s.promiseLibrary;
|
||||
if (!this.options.readPreference && changeDomain.s.readPreference) {
|
||||
this.options.readPreference = changeDomain.s.readPreference;
|
||||
}
|
||||
|
||||
// We need to get the operationTime as early as possible
|
||||
const isMaster = this.topology.lastIsMaster();
|
||||
if (!isMaster) {
|
||||
throw new MongoError('Topology does not have an ismaster yet.');
|
||||
}
|
||||
|
||||
this.operationTime = isMaster.operationTime;
|
||||
|
||||
// Create contained Change Stream cursor
|
||||
this.cursor = createChangeStreamCursor(this);
|
||||
|
||||
// Listen for any `change` listeners being added to ChangeStream
|
||||
this.on('newListener', eventName => {
|
||||
if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) {
|
||||
this.cursor.on('data', change =>
|
||||
processNewChange({ changeStream: this, change, eventEmitter: true })
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for all `change` listeners being removed from ChangeStream
|
||||
this.on('removeListener', eventName => {
|
||||
if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) {
|
||||
this.cursor.removeAllListeners('data');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the Change Stream
|
||||
* @function ChangeStream.prototype.hasNext
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
hasNext(callback) {
|
||||
return this.cursor.hasNext(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next available document from the Change Stream, returns null if no more documents are available.
|
||||
* @function ChangeStream.prototype.next
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
next(callback) {
|
||||
var self = this;
|
||||
if (this.isClosed()) {
|
||||
if (callback) return callback(new Error('Change Stream is not open.'), null);
|
||||
return self.promiseLibrary.reject(new Error('Change Stream is not open.'));
|
||||
}
|
||||
|
||||
return this.cursor
|
||||
.next()
|
||||
.then(change => processNewChange({ changeStream: self, change, callback }))
|
||||
.catch(error => processNewChange({ changeStream: self, error, callback }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the cursor closed
|
||||
* @method ChangeStream.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
isClosed() {
|
||||
if (this.cursor) {
|
||||
return this.cursor.isClosed();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the Change Stream
|
||||
* @method ChangeStream.prototype.close
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
close(callback) {
|
||||
if (!this.cursor) {
|
||||
if (callback) return callback();
|
||||
return this.promiseLibrary.resolve();
|
||||
}
|
||||
|
||||
// Tidy up the existing cursor
|
||||
var cursor = this.cursor;
|
||||
delete this.cursor;
|
||||
return cursor.close(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
|
||||
* @method
|
||||
* @param {Writable} destination The destination for writing data
|
||||
* @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options}
|
||||
* @return {null}
|
||||
*/
|
||||
pipe(destination, options) {
|
||||
if (!this.pipeDestinations) {
|
||||
this.pipeDestinations = [];
|
||||
}
|
||||
this.pipeDestinations.push(destination);
|
||||
return this.cursor.pipe(destination, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will remove the hooks set up for a previous pipe() call.
|
||||
* @param {Writable} [destination] The destination for writing data
|
||||
* @return {null}
|
||||
*/
|
||||
unpipe(destination) {
|
||||
if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) {
|
||||
this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1);
|
||||
}
|
||||
return this.cursor.unpipe(destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a modified Readable stream including a possible transform method.
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {function} [options.transform] A transformation method applied to each document emitted by the stream.
|
||||
* @return {Cursor}
|
||||
*/
|
||||
stream(options) {
|
||||
this.streamOptions = options;
|
||||
return this.cursor.stream(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
|
||||
* @return {null}
|
||||
*/
|
||||
pause() {
|
||||
return this.cursor.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will cause the readable stream to resume emitting data events.
|
||||
* @return {null}
|
||||
*/
|
||||
resume() {
|
||||
return this.cursor.resume();
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new change stream cursor based on self's configuration
|
||||
var createChangeStreamCursor = function(self) {
|
||||
if (self.resumeToken) {
|
||||
self.options.resumeAfter = self.resumeToken;
|
||||
}
|
||||
|
||||
var changeStreamCursor = buildChangeStreamAggregationCommand(self);
|
||||
|
||||
/**
|
||||
* Fired for each new matching change in the specified namespace. Attaching a `change`
|
||||
* event listener to a Change Stream will switch the stream into flowing mode. Data will
|
||||
* then be passed as soon as it is available.
|
||||
*
|
||||
* @event ChangeStream#change
|
||||
* @type {object}
|
||||
*/
|
||||
if (self.listenerCount('change') > 0) {
|
||||
changeStreamCursor.on('data', function(change) {
|
||||
processNewChange({ changeStream: self, change, eventEmitter: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Change stream close event
|
||||
*
|
||||
* @event ChangeStream#close
|
||||
* @type {null}
|
||||
*/
|
||||
changeStreamCursor.on('close', function() {
|
||||
self.emit('close');
|
||||
});
|
||||
|
||||
/**
|
||||
* Change stream end event
|
||||
*
|
||||
* @event ChangeStream#end
|
||||
* @type {null}
|
||||
*/
|
||||
changeStreamCursor.on('end', function() {
|
||||
self.emit('end');
|
||||
});
|
||||
|
||||
/**
|
||||
* Fired when the stream encounters an error.
|
||||
*
|
||||
* @event ChangeStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
changeStreamCursor.on('error', function(error) {
|
||||
processNewChange({ changeStream: self, error, eventEmitter: true });
|
||||
});
|
||||
|
||||
if (self.pipeDestinations) {
|
||||
const cursorStream = changeStreamCursor.stream(self.streamOptions);
|
||||
for (let pipeDestination in self.pipeDestinations) {
|
||||
cursorStream.pipe(pipeDestination);
|
||||
}
|
||||
}
|
||||
|
||||
return changeStreamCursor;
|
||||
};
|
||||
|
||||
function getResumeToken(self) {
|
||||
return self.resumeToken || self.options.resumeAfter;
|
||||
}
|
||||
|
||||
function getStartAtOperationTime(self) {
|
||||
const isMaster = self.topology.lastIsMaster() || {};
|
||||
return (
|
||||
isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime
|
||||
);
|
||||
}
|
||||
|
||||
var buildChangeStreamAggregationCommand = function(self) {
|
||||
const topology = self.topology;
|
||||
const namespace = self.namespace;
|
||||
const pipeline = self.pipeline;
|
||||
const options = self.options;
|
||||
const cursorNamespace = self.cursorNamespace;
|
||||
|
||||
var changeStreamStageOptions = {
|
||||
fullDocument: options.fullDocument || 'default'
|
||||
};
|
||||
|
||||
const resumeToken = getResumeToken(self);
|
||||
const startAtOperationTime = getStartAtOperationTime(self);
|
||||
if (resumeToken) {
|
||||
changeStreamStageOptions.resumeAfter = resumeToken;
|
||||
}
|
||||
|
||||
if (startAtOperationTime) {
|
||||
changeStreamStageOptions.startAtOperationTime = startAtOperationTime;
|
||||
}
|
||||
|
||||
// Map cursor options
|
||||
var cursorOptions = {};
|
||||
cursorOptionNames.forEach(function(optionName) {
|
||||
if (options[optionName]) {
|
||||
cursorOptions[optionName] = options[optionName];
|
||||
}
|
||||
});
|
||||
|
||||
if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) {
|
||||
changeStreamStageOptions.allChangesForCluster = true;
|
||||
}
|
||||
|
||||
var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }];
|
||||
|
||||
changeStreamPipeline = changeStreamPipeline.concat(pipeline);
|
||||
|
||||
var command = {
|
||||
aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1,
|
||||
pipeline: changeStreamPipeline,
|
||||
readConcern: { level: 'majority' },
|
||||
cursor: {
|
||||
batchSize: options.batchSize || 1
|
||||
}
|
||||
};
|
||||
|
||||
// Create and return the cursor
|
||||
return topology.cursor(cursorNamespace, command, cursorOptions);
|
||||
};
|
||||
|
||||
// This method performs a basic server selection loop, satisfying the requirements of
|
||||
// ChangeStream resumability until the new SDAM layer can be used.
|
||||
const SELECTION_TIMEOUT = 30000;
|
||||
function waitForTopologyConnected(topology, options, callback) {
|
||||
setTimeout(() => {
|
||||
if (options && options.start == null) options.start = process.hrtime();
|
||||
const start = options.start || process.hrtime();
|
||||
const timeout = options.timeout || SELECTION_TIMEOUT;
|
||||
const readPreference = options.readPreference;
|
||||
|
||||
if (topology.isConnected({ readPreference })) return callback(null, null);
|
||||
const hrElapsed = process.hrtime(start);
|
||||
const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6;
|
||||
if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection'));
|
||||
waitForTopologyConnected(topology, options, callback);
|
||||
}, 3000); // this is an arbitrary wait time to allow SDAM to transition
|
||||
}
|
||||
|
||||
// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream.
|
||||
function processNewChange(args) {
|
||||
const changeStream = args.changeStream;
|
||||
const error = args.error;
|
||||
const change = args.change;
|
||||
const callback = args.callback;
|
||||
const eventEmitter = args.eventEmitter || false;
|
||||
|
||||
// If the changeStream is closed, then it should not process a change.
|
||||
if (changeStream.isClosed()) {
|
||||
// We do not error in the eventEmitter case.
|
||||
if (eventEmitter) {
|
||||
return;
|
||||
}
|
||||
|
||||
const error = new MongoError('ChangeStream is closed');
|
||||
return typeof callback === 'function'
|
||||
? callback(error, null)
|
||||
: changeStream.promiseLibrary.reject(error);
|
||||
}
|
||||
|
||||
const topology = changeStream.topology;
|
||||
const options = changeStream.cursor.options;
|
||||
|
||||
if (error) {
|
||||
if (isResumableError(error) && !changeStream.attemptingResume) {
|
||||
changeStream.attemptingResume = true;
|
||||
|
||||
if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) {
|
||||
const startAtOperationTime = changeStream.cursor.cursorState.operationTime;
|
||||
changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options);
|
||||
}
|
||||
|
||||
// stop listening to all events from old cursor
|
||||
['data', 'close', 'end', 'error'].forEach(event =>
|
||||
changeStream.cursor.removeAllListeners(event)
|
||||
);
|
||||
|
||||
// close internal cursor, ignore errors
|
||||
changeStream.cursor.close();
|
||||
|
||||
// attempt recreating the cursor
|
||||
if (eventEmitter) {
|
||||
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
|
||||
if (err) return changeStream.emit('error', err);
|
||||
changeStream.cursor = createChangeStreamCursor(changeStream);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
|
||||
if (err) return callback(err, null);
|
||||
|
||||
changeStream.cursor = createChangeStreamCursor(changeStream);
|
||||
changeStream.next(callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
|
||||
if (err) return reject(err);
|
||||
resolve();
|
||||
});
|
||||
})
|
||||
.then(() => (changeStream.cursor = createChangeStreamCursor(changeStream)))
|
||||
.then(() => changeStream.next());
|
||||
}
|
||||
|
||||
if (eventEmitter) return changeStream.emit('error', error);
|
||||
if (typeof callback === 'function') return callback(error, null);
|
||||
return changeStream.promiseLibrary.reject(error);
|
||||
}
|
||||
|
||||
changeStream.attemptingResume = false;
|
||||
|
||||
// Cache the resume token if it is present. If it is not present return an error.
|
||||
if (!change || !change._id) {
|
||||
var noResumeTokenError = new Error(
|
||||
'A change stream document has been received that lacks a resume token (_id).'
|
||||
);
|
||||
|
||||
if (eventEmitter) return changeStream.emit('error', noResumeTokenError);
|
||||
if (typeof callback === 'function') return callback(noResumeTokenError, null);
|
||||
return changeStream.promiseLibrary.reject(noResumeTokenError);
|
||||
}
|
||||
|
||||
changeStream.resumeToken = change._id;
|
||||
|
||||
// Return the change
|
||||
if (eventEmitter) return changeStream.emit('change', change);
|
||||
if (typeof callback === 'function') return callback(error, change);
|
||||
return changeStream.promiseLibrary.resolve(change);
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback ChangeStream~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
module.exports = ChangeStream;
|
2099
node_modules/mongodb/lib/collection.js
generated
vendored
Normal file
2099
node_modules/mongodb/lib/collection.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
334
node_modules/mongodb/lib/command_cursor.js
generated
vendored
Normal file
334
node_modules/mongodb/lib/command_cursor.js
generated
vendored
Normal file
@@ -0,0 +1,334 @@
|
||||
'use strict';
|
||||
|
||||
const inherits = require('util').inherits;
|
||||
const ReadPreference = require('mongodb-core').ReadPreference;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const Readable = require('stream').Readable;
|
||||
const CoreCursor = require('./cursor');
|
||||
|
||||
/**
|
||||
* @fileOverview The **CommandCursor** class is an internal class that embodies a
|
||||
* generalized cursor based on a MongoDB command allowing for iteration over the
|
||||
* results returned. It supports one by one document iteration, conversion to an
|
||||
* array or can be iterated as a Node 0.10.X or higher stream
|
||||
*
|
||||
* **CommandCursor Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Create a collection we want to drop later
|
||||
* const col = client.db(dbName).collection('listCollectionsExample1');
|
||||
* // Insert a bunch of documents
|
||||
* col.insert([{a:1, b:1}
|
||||
* , {a:2, b:2}, {a:3, b:3}
|
||||
* , {a:4, b:4}], {w:1}, function(err, result) {
|
||||
* test.equal(null, err);
|
||||
* // List the database collections available
|
||||
* db.listCollections().toArray(function(err, items) {
|
||||
* test.equal(null, err);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Namespace provided by the browser.
|
||||
* @external Readable
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class CommandCursor
|
||||
* @extends external:Readable
|
||||
* @fires CommandCursor#data
|
||||
* @fires CommandCursor#end
|
||||
* @fires CommandCursor#close
|
||||
* @fires CommandCursor#readable
|
||||
* @return {CommandCursor} an CommandCursor instance.
|
||||
*/
|
||||
var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
|
||||
CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
|
||||
var state = CommandCursor.INIT;
|
||||
var streamOptions = {};
|
||||
|
||||
// MaxTimeMS
|
||||
var maxTimeMS = null;
|
||||
|
||||
// Get the promiseLibrary
|
||||
var promiseLibrary = options.promiseLibrary || Promise;
|
||||
|
||||
// Set up
|
||||
Readable.call(this, { objectMode: true });
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
// MaxTimeMS
|
||||
maxTimeMS: maxTimeMS,
|
||||
// State
|
||||
state: state,
|
||||
// Stream options
|
||||
streamOptions: streamOptions,
|
||||
// BSON
|
||||
bson: bson,
|
||||
// Namespace
|
||||
ns: ns,
|
||||
// Command
|
||||
cmd: cmd,
|
||||
// Options
|
||||
options: options,
|
||||
// Topology
|
||||
topology: topology,
|
||||
// Topology Options
|
||||
topologyOptions: topologyOptions,
|
||||
// Promise library
|
||||
promiseLibrary: promiseLibrary,
|
||||
// Optional ClientSession
|
||||
session: options.session
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* CommandCursor stream data event, fired for each document in the cursor.
|
||||
*
|
||||
* @event CommandCursor#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream end event
|
||||
*
|
||||
* @event CommandCursor#end
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream close event
|
||||
*
|
||||
* @event CommandCursor#close
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream readable event
|
||||
*
|
||||
* @event CommandCursor#readable
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
// Inherit from Readable
|
||||
inherits(CommandCursor, Readable);
|
||||
|
||||
// Set the methods to inherit from prototype
|
||||
var methodsToInherit = [
|
||||
'_next',
|
||||
'next',
|
||||
'hasNext',
|
||||
'each',
|
||||
'forEach',
|
||||
'toArray',
|
||||
'rewind',
|
||||
'bufferedCount',
|
||||
'readBufferedDocuments',
|
||||
'close',
|
||||
'isClosed',
|
||||
'kill',
|
||||
'setCursorBatchSize',
|
||||
'_find',
|
||||
'_getmore',
|
||||
'_killcursor',
|
||||
'isDead',
|
||||
'explain',
|
||||
'isNotified',
|
||||
'isKilled',
|
||||
'_endSession',
|
||||
'_initImplicitSession'
|
||||
];
|
||||
|
||||
// Only inherit the types we need
|
||||
for (var i = 0; i < methodsToInherit.length; i++) {
|
||||
CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the ReadPreference for the cursor.
|
||||
* @method
|
||||
* @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
|
||||
* @throws {MongoError}
|
||||
* @return {Cursor}
|
||||
*/
|
||||
CommandCursor.prototype.setReadPreference = function(readPreference) {
|
||||
if (this.s.state === CommandCursor.CLOSED || this.isDead()) {
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
}
|
||||
|
||||
if (this.s.state !== CommandCursor.INIT) {
|
||||
throw MongoError.create({
|
||||
message: 'cannot change cursor readPreference after cursor has been accessed',
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
|
||||
if (readPreference instanceof ReadPreference) {
|
||||
this.s.options.readPreference = readPreference;
|
||||
} else if (typeof readPreference === 'string') {
|
||||
this.s.options.readPreference = new ReadPreference(readPreference);
|
||||
} else {
|
||||
throw new TypeError('Invalid read preference: ' + readPreference);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the batch size for the cursor.
|
||||
* @method
|
||||
* @param {number} value The batchSize for the cursor.
|
||||
* @throws {MongoError}
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
CommandCursor.prototype.batchSize = function(value) {
|
||||
if (this.s.state === CommandCursor.CLOSED || this.isDead())
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
if (typeof value !== 'number')
|
||||
throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
|
||||
if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
|
||||
this.setCursorBatchSize(value);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a maxTimeMS stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state maxTimeMS value.
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
CommandCursor.prototype.maxTimeMS = function(value) {
|
||||
if (this.s.topology.lastIsMaster().minWireVersion > 2) {
|
||||
this.s.cmd.maxTimeMS = value;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the cursor logger
|
||||
* @method
|
||||
* @return {Logger} return the cursor logger
|
||||
* @ignore
|
||||
*/
|
||||
CommandCursor.prototype.getLogger = function() {
|
||||
return this.logger;
|
||||
};
|
||||
|
||||
CommandCursor.prototype.get = CommandCursor.prototype.toArray;
|
||||
|
||||
/**
|
||||
* Get the next available document from the cursor, returns null if no more documents are available.
|
||||
* @function CommandCursor.prototype.next
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the cursor
|
||||
* @function CommandCursor.prototype.hasNext
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback CommandCursor~toArrayResultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object[]} documents All the documents the satisfy the cursor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns an array of documents. The caller is responsible for making sure that there
|
||||
* is enough memory to store the results. Note that the array only contain partial
|
||||
* results when this cursor had been previouly accessed.
|
||||
* @method CommandCursor.prototype.toArray
|
||||
* @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback CommandCursor~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
|
||||
* not all of the elements will be iterated if this cursor had been previouly accessed.
|
||||
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
|
||||
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
|
||||
* at any given time if batch size is specified. Otherwise, the caller is responsible
|
||||
* for making sure that the entire result can fit the memory.
|
||||
* @method CommandCursor.prototype.each
|
||||
* @param {CommandCursor~resultCallback} callback The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Close the cursor, sending a KillCursor command and emitting close.
|
||||
* @method CommandCursor.prototype.close
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Is the cursor closed
|
||||
* @method CommandCursor.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clone the cursor
|
||||
* @function CommandCursor.prototype.clone
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resets the cursor
|
||||
* @function CommandCursor.prototype.rewind
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for the forEach iterator method
|
||||
* @callback CommandCursor~iteratorCallback
|
||||
* @param {Object} doc An emitted document for the iterator
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback error format for the forEach iterator method
|
||||
* @callback CommandCursor~endCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Iterates over all the documents for this cursor using the iterator, callback pattern.
|
||||
* @method CommandCursor.prototype.forEach
|
||||
* @param {CommandCursor~iteratorCallback} iterator The iteration callback.
|
||||
* @param {CommandCursor~endCallback} callback The end callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
CommandCursor.INIT = 0;
|
||||
CommandCursor.OPEN = 1;
|
||||
CommandCursor.CLOSED = 2;
|
||||
|
||||
module.exports = CommandCursor;
|
10
node_modules/mongodb/lib/constants.js
generated
vendored
Normal file
10
node_modules/mongodb/lib/constants.js
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces',
|
||||
SYSTEM_INDEX_COLLECTION: 'system.indexes',
|
||||
SYSTEM_PROFILE_COLLECTION: 'system.profile',
|
||||
SYSTEM_USER_COLLECTION: 'system.users',
|
||||
SYSTEM_COMMAND_COLLECTION: '$cmd',
|
||||
SYSTEM_JS_COLLECTION: 'system.js'
|
||||
};
|
1152
node_modules/mongodb/lib/cursor.js
generated
vendored
Normal file
1152
node_modules/mongodb/lib/cursor.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
985
node_modules/mongodb/lib/db.js
generated
vendored
Normal file
985
node_modules/mongodb/lib/db.js
generated
vendored
Normal file
@@ -0,0 +1,985 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const inherits = require('util').inherits;
|
||||
const getSingleProperty = require('./utils').getSingleProperty;
|
||||
const CommandCursor = require('./command_cursor');
|
||||
const handleCallback = require('./utils').handleCallback;
|
||||
const filterOptions = require('./utils').filterOptions;
|
||||
const toError = require('./utils').toError;
|
||||
const ReadPreference = require('mongodb-core').ReadPreference;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const ObjectID = require('mongodb-core').ObjectID;
|
||||
const Logger = require('mongodb-core').Logger;
|
||||
const Collection = require('./collection');
|
||||
const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern;
|
||||
const executeOperation = require('./utils').executeOperation;
|
||||
const applyWriteConcern = require('./utils').applyWriteConcern;
|
||||
const resolveReadPreference = require('./utils').resolveReadPreference;
|
||||
const ChangeStream = require('./change_stream');
|
||||
const deprecate = require('util').deprecate;
|
||||
const deprecateOptions = require('./utils').deprecateOptions;
|
||||
const CONSTANTS = require('./constants');
|
||||
|
||||
// Operations
|
||||
const addUser = require('./operations/db_ops').addUser;
|
||||
const collections = require('./operations/db_ops').collections;
|
||||
const createCollection = require('./operations/db_ops').createCollection;
|
||||
const createIndex = require('./operations/db_ops').createIndex;
|
||||
const createListener = require('./operations/db_ops').createListener;
|
||||
const dropCollection = require('./operations/db_ops').dropCollection;
|
||||
const dropDatabase = require('./operations/db_ops').dropDatabase;
|
||||
const ensureIndex = require('./operations/db_ops').ensureIndex;
|
||||
const evaluate = require('./operations/db_ops').evaluate;
|
||||
const executeCommand = require('./operations/db_ops').executeCommand;
|
||||
const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand;
|
||||
const indexInformation = require('./operations/db_ops').indexInformation;
|
||||
const listCollectionsTransforms = require('./operations/db_ops').listCollectionsTransforms;
|
||||
const profilingInfo = require('./operations/db_ops').profilingInfo;
|
||||
const profilingLevel = require('./operations/db_ops').profilingLevel;
|
||||
const removeUser = require('./operations/db_ops').removeUser;
|
||||
const setProfilingLevel = require('./operations/db_ops').setProfilingLevel;
|
||||
const validateDatabaseName = require('./operations/db_ops').validateDatabaseName;
|
||||
|
||||
/**
|
||||
* @fileOverview The **Db** class is a class that represents a MongoDB Database.
|
||||
*
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Select the database by name
|
||||
* const testDb = client.db(dbName);
|
||||
* client.close();
|
||||
* });
|
||||
*/
|
||||
|
||||
// Allowed parameters
|
||||
const legalOptionNames = [
|
||||
'w',
|
||||
'wtimeout',
|
||||
'fsync',
|
||||
'j',
|
||||
'readPreference',
|
||||
'readPreferenceTags',
|
||||
'native_parser',
|
||||
'forceServerObjectId',
|
||||
'pkFactory',
|
||||
'serializeFunctions',
|
||||
'raw',
|
||||
'bufferMaxEntries',
|
||||
'authSource',
|
||||
'ignoreUndefined',
|
||||
'promoteLongs',
|
||||
'promiseLibrary',
|
||||
'readConcern',
|
||||
'retryMiliSeconds',
|
||||
'numberOfRetries',
|
||||
'parentDb',
|
||||
'noListener',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'promoteBuffers',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'compression',
|
||||
'retryWrites'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates a new Db instance
|
||||
* @class
|
||||
* @param {string} databaseName The name of the database this instance represents.
|
||||
* @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string} [options.authSource] If the database authentication is dependent on another databaseName.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
|
||||
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
|
||||
* @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
|
||||
* @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
|
||||
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
|
||||
* @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
|
||||
* @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
|
||||
* @property {string} databaseName The name of the database this instance represents.
|
||||
* @property {object} options The options associated with the db instance.
|
||||
* @property {boolean} native_parser The current value of the parameter native_parser.
|
||||
* @property {boolean} slaveOk The current slaveOk value for the db instance.
|
||||
* @property {object} writeConcern The current write concern values.
|
||||
* @property {object} topology Access the topology object (single server, replicaset or mongos).
|
||||
* @fires Db#close
|
||||
* @fires Db#reconnect
|
||||
* @fires Db#error
|
||||
* @fires Db#timeout
|
||||
* @fires Db#parseError
|
||||
* @fires Db#fullsetup
|
||||
* @return {Db} a Db instance.
|
||||
*/
|
||||
function Db(databaseName, topology, options) {
|
||||
options = options || {};
|
||||
if (!(this instanceof Db)) return new Db(databaseName, topology, options);
|
||||
EventEmitter.call(this);
|
||||
|
||||
// Get the promiseLibrary
|
||||
const promiseLibrary = options.promiseLibrary || Promise;
|
||||
|
||||
// Filter the options
|
||||
options = filterOptions(options, legalOptionNames);
|
||||
|
||||
// Ensure we put the promiseLib in the options
|
||||
options.promiseLibrary = promiseLibrary;
|
||||
|
||||
// Internal state of the db object
|
||||
this.s = {
|
||||
// Database name
|
||||
databaseName: databaseName,
|
||||
// DbCache
|
||||
dbCache: {},
|
||||
// Children db's
|
||||
children: [],
|
||||
// Topology
|
||||
topology: topology,
|
||||
// Options
|
||||
options: options,
|
||||
// Logger instance
|
||||
logger: Logger('Db', options),
|
||||
// Get the bson parser
|
||||
bson: topology ? topology.bson : null,
|
||||
// Unpack read preference
|
||||
readPreference: options.readPreference,
|
||||
// Set buffermaxEntries
|
||||
bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1,
|
||||
// Parent db (if chained)
|
||||
parentDb: options.parentDb || null,
|
||||
// Set up the primary key factory or fallback to ObjectID
|
||||
pkFactory: options.pkFactory || ObjectID,
|
||||
// Get native parser
|
||||
nativeParser: options.nativeParser || options.native_parser,
|
||||
// Promise library
|
||||
promiseLibrary: promiseLibrary,
|
||||
// No listener
|
||||
noListener: typeof options.noListener === 'boolean' ? options.noListener : false,
|
||||
// ReadConcern
|
||||
readConcern: options.readConcern
|
||||
};
|
||||
|
||||
// Ensure we have a valid db name
|
||||
validateDatabaseName(this.s.databaseName);
|
||||
|
||||
// Add a read Only property
|
||||
getSingleProperty(this, 'serverConfig', this.s.topology);
|
||||
getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries);
|
||||
getSingleProperty(this, 'databaseName', this.s.databaseName);
|
||||
|
||||
// This is a child db, do not register any listeners
|
||||
if (options.parentDb) return;
|
||||
if (this.s.noListener) return;
|
||||
|
||||
// Add listeners
|
||||
topology.on('error', createListener(this, 'error', this));
|
||||
topology.on('timeout', createListener(this, 'timeout', this));
|
||||
topology.on('close', createListener(this, 'close', this));
|
||||
topology.on('parseError', createListener(this, 'parseError', this));
|
||||
topology.once('open', createListener(this, 'open', this));
|
||||
topology.once('fullsetup', createListener(this, 'fullsetup', this));
|
||||
topology.once('all', createListener(this, 'all', this));
|
||||
topology.on('reconnect', createListener(this, 'reconnect', this));
|
||||
}
|
||||
|
||||
inherits(Db, EventEmitter);
|
||||
|
||||
// Topology
|
||||
Object.defineProperty(Db.prototype, 'topology', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.topology;
|
||||
}
|
||||
});
|
||||
|
||||
// Options
|
||||
Object.defineProperty(Db.prototype, 'options', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.options;
|
||||
}
|
||||
});
|
||||
|
||||
// slaveOk specified
|
||||
Object.defineProperty(Db.prototype, 'slaveOk', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
if (
|
||||
this.s.options.readPreference != null &&
|
||||
(this.s.options.readPreference !== 'primary' ||
|
||||
this.s.options.readPreference.mode !== 'primary')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// get the write Concern
|
||||
Object.defineProperty(Db.prototype, 'writeConcern', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
const ops = {};
|
||||
if (this.s.options.w != null) ops.w = this.s.options.w;
|
||||
if (this.s.options.j != null) ops.j = this.s.options.j;
|
||||
if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
|
||||
if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
|
||||
return ops;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
* @method
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.command = function(command, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = Object.assign({}, options);
|
||||
|
||||
return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the Admin db instance
|
||||
* @method
|
||||
* @return {Admin} return the new Admin db instance
|
||||
*/
|
||||
Db.prototype.admin = function() {
|
||||
const Admin = require('./admin');
|
||||
|
||||
return new Admin(this, this.s.topology, this.s.promiseLibrary);
|
||||
};
|
||||
|
||||
/**
|
||||
* The callback format for the collection method, must be used if strict is specified
|
||||
* @callback Db~collectionResultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {Collection} collection The collection instance.
|
||||
*/
|
||||
|
||||
const collectionKeys = [
|
||||
'pkFactory',
|
||||
'readPreference',
|
||||
'serializeFunctions',
|
||||
'strict',
|
||||
'readConcern',
|
||||
'ignoreUndefined',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'promoteLongs'
|
||||
];
|
||||
|
||||
/**
|
||||
* Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you
|
||||
* can use it without a callback in the following way: `const collection = db.collection('mycollection');`
|
||||
*
|
||||
* @method
|
||||
* @param {string} name the collection name we wish to access.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
|
||||
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
|
||||
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
|
||||
* @param {Db~collectionResultCallback} [callback] The collection result callback
|
||||
* @return {Collection} return the new Collection instance if not in strict mode
|
||||
*/
|
||||
Db.prototype.collection = function(name, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
options = Object.assign({}, options);
|
||||
|
||||
// Set the promise library
|
||||
options.promiseLibrary = this.s.promiseLibrary;
|
||||
|
||||
// If we have not set a collection level readConcern set the db level one
|
||||
options.readConcern = options.readConcern || this.s.readConcern;
|
||||
|
||||
// Do we have ignoreUndefined set
|
||||
if (this.s.options.ignoreUndefined) {
|
||||
options.ignoreUndefined = this.s.options.ignoreUndefined;
|
||||
}
|
||||
|
||||
// Merge in all needed options and ensure correct writeConcern merging from db level
|
||||
options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true);
|
||||
|
||||
// Execute
|
||||
if (options == null || !options.strict) {
|
||||
try {
|
||||
const collection = new Collection(
|
||||
this,
|
||||
this.s.topology,
|
||||
this.s.databaseName,
|
||||
name,
|
||||
this.s.pkFactory,
|
||||
options
|
||||
);
|
||||
if (callback) callback(null, collection);
|
||||
return collection;
|
||||
} catch (err) {
|
||||
if (err instanceof MongoError && callback) return callback(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Strict mode
|
||||
if (typeof callback !== 'function') {
|
||||
throw toError(`A callback is required in strict mode. While getting collection ${name}`);
|
||||
}
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (this.serverConfig && this.serverConfig.isDestroyed()) {
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
}
|
||||
|
||||
const listCollectionOptions = Object.assign({}, options, { nameOnly: true });
|
||||
|
||||
// Strict mode
|
||||
this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => {
|
||||
if (err != null) return handleCallback(callback, err, null);
|
||||
if (collections.length === 0)
|
||||
return handleCallback(
|
||||
callback,
|
||||
toError(`Collection ${name} does not exist. Currently in strict mode.`),
|
||||
null
|
||||
);
|
||||
|
||||
try {
|
||||
return handleCallback(
|
||||
callback,
|
||||
null,
|
||||
new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options)
|
||||
);
|
||||
} catch (err) {
|
||||
return handleCallback(callback, err, null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new collection on a server with the specified options. Use this to create capped collections.
|
||||
* More information about command options available at https://docs.mongodb.com/manual/reference/command/create/
|
||||
*
|
||||
* @method
|
||||
* @param {string} name the collection name we wish to access.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
|
||||
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
|
||||
* @param {boolean} [options.capped=false] Create a capped collection.
|
||||
* @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0
|
||||
* @param {number} [options.size] The size of the capped collection in bytes.
|
||||
* @param {number} [options.max] The maximum number of documents in the capped collection.
|
||||
* @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.
|
||||
* @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.
|
||||
* @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.
|
||||
* @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.
|
||||
* @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.
|
||||
* @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.
|
||||
* @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.
|
||||
* @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.
|
||||
* @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~collectionResultCallback} [callback] The results callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.createCollection = deprecateOptions(
|
||||
{
|
||||
name: 'Db.createCollection',
|
||||
deprecatedOptions: ['autoIndexId'],
|
||||
optionsIndex: 1
|
||||
},
|
||||
function(name, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;
|
||||
|
||||
return executeOperation(this.s.topology, createCollection, [this, name, options, callback]);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Get all the db statistics.
|
||||
*
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.scale] Divide the returned sizes by scale value.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The collection result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.stats = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
// Build command object
|
||||
const commandObject = { dbStats: true };
|
||||
// Check if we have the scale value
|
||||
if (options['scale'] != null) commandObject['scale'] = options['scale'];
|
||||
|
||||
// If we have a readPreference set
|
||||
if (options.readPreference == null && this.s.readPreference) {
|
||||
options.readPreference = this.s.readPreference;
|
||||
}
|
||||
|
||||
// Execute the command
|
||||
return this.command(commandObject, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the list of all collection information for the specified db.
|
||||
*
|
||||
* @method
|
||||
* @param {object} [filter={}] Query to filter collections by
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info
|
||||
* @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
Db.prototype.listCollections = function(filter, options) {
|
||||
filter = filter || {};
|
||||
options = options || {};
|
||||
|
||||
// Shallow clone the object
|
||||
options = Object.assign({}, options);
|
||||
// Set the promise library
|
||||
options.promiseLibrary = this.s.promiseLibrary;
|
||||
|
||||
// Ensure valid readPreference
|
||||
options.readPreference = resolveReadPreference(options, {
|
||||
db: this,
|
||||
default: ReadPreference.primary
|
||||
});
|
||||
|
||||
// Cursor options
|
||||
let cursor = options.batchSize ? { batchSize: options.batchSize } : {};
|
||||
|
||||
// We have a list collections command
|
||||
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
|
||||
const nameOnly = typeof options.nameOnly === 'boolean' ? options.nameOnly : false;
|
||||
// Build the command
|
||||
const command = { listCollections: true, filter, cursor, nameOnly };
|
||||
// Set the AggregationCursor constructor
|
||||
options.cursorFactory = CommandCursor;
|
||||
// Create the cursor
|
||||
cursor = this.s.topology.cursor(`${this.s.databaseName}.$cmd`, command, options);
|
||||
// Do we have a readPreference, apply it
|
||||
if (options.readPreference) {
|
||||
cursor.setReadPreference(options.readPreference);
|
||||
}
|
||||
// Return the cursor
|
||||
return cursor;
|
||||
}
|
||||
|
||||
// We cannot use the listCollectionsCommand
|
||||
if (!this.serverConfig.capabilities().hasListCollectionsCommand) {
|
||||
// If we have legacy mode and have not provided a full db name filter it
|
||||
if (
|
||||
typeof filter.name === 'string' &&
|
||||
!new RegExp('^' + this.databaseName + '\\.').test(filter.name)
|
||||
) {
|
||||
filter = Object.assign({}, filter);
|
||||
filter.name = `${this.s.databaseName}.${filter.name}`;
|
||||
}
|
||||
}
|
||||
|
||||
// No filter, filter by current database
|
||||
if (filter == null) {
|
||||
filter.name = `/${this.s.databaseName}/`;
|
||||
}
|
||||
|
||||
// Rewrite the filter to use $and to filter out indexes
|
||||
if (filter.name) {
|
||||
filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] };
|
||||
} else {
|
||||
filter = { name: /^((?!\$).)*$/ };
|
||||
}
|
||||
|
||||
// Return options
|
||||
const _options = { transforms: listCollectionsTransforms(this.s.databaseName) };
|
||||
// Get the cursor
|
||||
cursor = this.collection(CONSTANTS.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options);
|
||||
// Do we have a readPreference, apply it
|
||||
if (options.readPreference) cursor.setReadPreference(options.readPreference);
|
||||
// Set the passed in batch size if one was provided
|
||||
if (options.batchSize) cursor = cursor.batchSize(options.batchSize);
|
||||
// We have a fallback mode using legacy systems collections
|
||||
return cursor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Evaluate JavaScript on the server
|
||||
*
|
||||
* @method
|
||||
* @param {Code} code JavaScript to execute on server.
|
||||
* @param {(object|array)} parameters The parameters for the call.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The results callback
|
||||
* @deprecated Eval is deprecated on MongoDB 3.2 and forward
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.eval = deprecate(function(code, parameters, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
parameters = args.length ? args.shift() : parameters;
|
||||
options = args.length ? args.shift() || {} : {};
|
||||
|
||||
return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]);
|
||||
}, 'Db.eval is deprecated as of MongoDB version 3.2');
|
||||
|
||||
/**
|
||||
* Rename a collection.
|
||||
*
|
||||
* @method
|
||||
* @param {string} fromCollection Name of current collection to rename.
|
||||
* @param {string} toCollection New name of of the collection.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~collectionResultCallback} [callback] The results callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
// Add return new collection
|
||||
options.new_collection = true;
|
||||
|
||||
const collection = this.collection(fromCollection);
|
||||
return executeOperation(this.s.topology, collection.rename.bind(collection), [
|
||||
toCollection,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Drop a collection from the database, removing it permanently. New accesses will create a new collection.
|
||||
*
|
||||
* @method
|
||||
* @param {string} name Name of collection to drop
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The results callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.dropCollection = function(name, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
// Command to execute
|
||||
const cmd = { drop: name };
|
||||
|
||||
// Decorate with write concern
|
||||
applyWriteConcern(cmd, { db: this }, options);
|
||||
|
||||
// options
|
||||
const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY });
|
||||
if (options.session) opts.session = options.session;
|
||||
|
||||
return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Drop a database, removing it permanently from the server.
|
||||
*
|
||||
* @method
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The results callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.dropDatabase = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
// Drop database command
|
||||
const cmd = { dropDatabase: 1 };
|
||||
|
||||
// Decorate with write concern
|
||||
applyWriteConcern(cmd, { db: this }, options);
|
||||
|
||||
// Ensure primary only
|
||||
const finalOptions = Object.assign({}, this.s.options, {
|
||||
readPreference: ReadPreference.PRIMARY
|
||||
});
|
||||
|
||||
if (options.session) {
|
||||
finalOptions.session = options.session;
|
||||
}
|
||||
|
||||
return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch all collections for the current db.
|
||||
*
|
||||
* @method
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~collectionsResultCallback} [callback] The results callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.collections = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, collections, [this, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs a command on the database as admin.
|
||||
* @method
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
options.readPreference = resolveReadPreference(options);
|
||||
|
||||
return executeOperation(this.s.topology, executeDbAdminCommand, [
|
||||
this,
|
||||
selector,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an index on the db and collection.
|
||||
* @method
|
||||
* @param {string} name Name of the collection to create the index on.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.unique=false] Creates an unique index.
|
||||
* @param {boolean} [options.sparse=false] Creates a sparse index.
|
||||
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
|
||||
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
|
||||
* @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
|
||||
* @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
|
||||
* @param {number} [options.v] Specify the format version of the indexes.
|
||||
* @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
|
||||
* @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
|
||||
* @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options ? Object.assign({}, options) : {};
|
||||
|
||||
return executeOperation(this.s.topology, createIndex, [
|
||||
this,
|
||||
name,
|
||||
fieldOrSpec,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Ensures that an index exists, if it does not it creates it
|
||||
* @method
|
||||
* @deprecated since version 2.0
|
||||
* @param {string} name The index name
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.unique=false] Creates an unique index.
|
||||
* @param {boolean} [options.sparse=false] Creates a sparse index.
|
||||
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
|
||||
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
|
||||
* @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
|
||||
* @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
|
||||
* @param {number} [options.v] Specify the format version of the indexes.
|
||||
* @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
|
||||
* @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, ensureIndex, [
|
||||
this,
|
||||
name,
|
||||
fieldOrSpec,
|
||||
options,
|
||||
callback
|
||||
]);
|
||||
}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0');
|
||||
|
||||
Db.prototype.addChild = function(db) {
|
||||
if (this.s.parentDb) return this.s.parentDb.addChild(db);
|
||||
this.s.children.push(db);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a user to the database.
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {string} password The password.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)
|
||||
* @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.addUser = function(username, password, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, addUser, [this, username, password, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove a user from a database
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.removeUser = function(username, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, removeUser, [this, username, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the current profiling level of MongoDB
|
||||
*
|
||||
* @param {string} level The new profiling level (off, slow_only, all).
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.setProfilingLevel = function(level, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, setProfilingLevel, [this, level, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrive the current profiling information for MongoDB
|
||||
*
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
* @deprecated Query the system.profile collection directly.
|
||||
*/
|
||||
Db.prototype.profilingInfo = deprecate(function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, profilingInfo, [this, options, callback]);
|
||||
}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.');
|
||||
|
||||
/**
|
||||
* Retrieve the current profiling Level for MongoDB
|
||||
*
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.profilingLevel = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, profilingLevel, [this, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves this collections index info.
|
||||
* @method
|
||||
* @param {string} name The name of the collection.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.full=false] Returns the full raw index information.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Db.prototype.indexInformation = function(name, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(this.s.topology, indexInformation, [this, name, options, callback]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unref all sockets
|
||||
* @method
|
||||
*/
|
||||
Db.prototype.unref = function() {
|
||||
this.s.topology.unref();
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections.
|
||||
* @method
|
||||
* @since 3.1.0
|
||||
* @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
|
||||
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
|
||||
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
|
||||
* @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
|
||||
* @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @return {ChangeStream} a ChangeStream instance.
|
||||
*/
|
||||
Db.prototype.watch = function(pipeline, options) {
|
||||
pipeline = pipeline || [];
|
||||
options = options || {};
|
||||
|
||||
// Allow optionally not specifying a pipeline
|
||||
if (!Array.isArray(pipeline)) {
|
||||
options = pipeline;
|
||||
pipeline = [];
|
||||
}
|
||||
|
||||
return new ChangeStream(this, pipeline, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the db logger
|
||||
* @method
|
||||
* @return {Logger} return the db logger
|
||||
* @ignore
|
||||
*/
|
||||
Db.prototype.getLogger = function() {
|
||||
return this.s.logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* Db close event
|
||||
*
|
||||
* Emitted after a socket closed against a single server or mongos proxy.
|
||||
*
|
||||
* @event Db#close
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Db reconnect event
|
||||
*
|
||||
* * Server: Emitted when the driver has reconnected and re-authenticated.
|
||||
* * ReplicaSet: N/A
|
||||
* * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
|
||||
*
|
||||
* @event Db#reconnect
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Db error event
|
||||
*
|
||||
* Emitted after an error occurred against a single server or mongos proxy.
|
||||
*
|
||||
* @event Db#error
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Db timeout event
|
||||
*
|
||||
* Emitted after a socket timeout occurred against a single server or mongos proxy.
|
||||
*
|
||||
* @event Db#timeout
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Db parseError event
|
||||
*
|
||||
* The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.
|
||||
*
|
||||
* @event Db#parseError
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.
|
||||
*
|
||||
* * Server: Emitted when the driver has connected to the single server and has authenticated.
|
||||
* * ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
|
||||
* * Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
|
||||
*
|
||||
* @event Db#fullsetup
|
||||
* @type {Db}
|
||||
*/
|
||||
|
||||
// Constants
|
||||
Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
|
||||
Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
|
||||
Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
|
||||
Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
|
||||
Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
|
||||
Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
|
||||
|
||||
module.exports = Db;
|
43
node_modules/mongodb/lib/error.js
generated
vendored
Normal file
43
node_modules/mongodb/lib/error.js
generated
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
const MongoNetworkError = require('mongodb-core').MongoNetworkError;
|
||||
const mongoErrorContextSymbol = require('mongodb-core').mongoErrorContextSymbol;
|
||||
|
||||
const GET_MORE_NON_RESUMABLE_CODES = new Set([
|
||||
136, // CappedPositionLost
|
||||
237, // CursorKilled
|
||||
11601 // Interrupted
|
||||
]);
|
||||
|
||||
// From spec@https://github.com/mongodb/specifications/blob/35e466ddf25059cb30e4113de71cdebd3754657f/source/change-streams.rst#resumable-error:
|
||||
//
|
||||
// An error is considered resumable if it meets any of the following criteria:
|
||||
// - any error encountered which is not a server error (e.g. a timeout error or network error)
|
||||
// - any server error response from a getMore command excluding those containing the following error codes
|
||||
// - Interrupted: 11601
|
||||
// - CappedPositionLost: 136
|
||||
// - CursorKilled: 237
|
||||
// - a server error response with an error message containing the substring "not master" or "node is recovering"
|
||||
//
|
||||
// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors.
|
||||
|
||||
function isGetMoreError(error) {
|
||||
if (error[mongoErrorContextSymbol]) {
|
||||
return error[mongoErrorContextSymbol].isGetMore;
|
||||
}
|
||||
}
|
||||
|
||||
function isResumableError(error) {
|
||||
if (!isGetMoreError(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !!(
|
||||
error instanceof MongoNetworkError ||
|
||||
!GET_MORE_NON_RESUMABLE_CODES.has(error.code) ||
|
||||
error.message.match(/not master/) ||
|
||||
error.message.match(/node is recovering/)
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError };
|
415
node_modules/mongodb/lib/gridfs-stream/download.js
generated
vendored
Normal file
415
node_modules/mongodb/lib/gridfs-stream/download.js
generated
vendored
Normal file
@@ -0,0 +1,415 @@
|
||||
'use strict';
|
||||
|
||||
var stream = require('stream'),
|
||||
util = require('util');
|
||||
|
||||
module.exports = GridFSBucketReadStream;
|
||||
|
||||
/**
|
||||
* A readable stream that enables you to read buffers from GridFS.
|
||||
*
|
||||
* Do not instantiate this class directly. Use `openDownloadStream()` instead.
|
||||
*
|
||||
* @class
|
||||
* @param {Collection} chunks Handle for chunks collection
|
||||
* @param {Collection} files Handle for files collection
|
||||
* @param {Object} readPreference The read preference to use
|
||||
* @param {Object} filter The query to use to find the file document
|
||||
* @param {Object} [options] Optional settings.
|
||||
* @param {Number} [options.sort] Optional sort for the file find query
|
||||
* @param {Number} [options.skip] Optional skip for the file find query
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @fires GridFSBucketReadStream#error
|
||||
* @fires GridFSBucketReadStream#file
|
||||
* @return {GridFSBucketReadStream} a GridFSBucketReadStream instance.
|
||||
*/
|
||||
|
||||
function GridFSBucketReadStream(chunks, files, readPreference, filter, options) {
|
||||
this.s = {
|
||||
bytesRead: 0,
|
||||
chunks: chunks,
|
||||
cursor: null,
|
||||
expected: 0,
|
||||
files: files,
|
||||
filter: filter,
|
||||
init: false,
|
||||
expectedEnd: 0,
|
||||
file: null,
|
||||
options: options,
|
||||
readPreference: readPreference
|
||||
};
|
||||
|
||||
stream.Readable.call(this);
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucketReadStream, stream.Readable);
|
||||
|
||||
/**
|
||||
* An error occurred
|
||||
*
|
||||
* @event GridFSBucketReadStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fires when the stream loaded the file document corresponding to the
|
||||
* provided id.
|
||||
*
|
||||
* @event GridFSBucketReadStream#file
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when a chunk of data is available to be consumed.
|
||||
*
|
||||
* @event GridFSBucketReadStream#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fired when the stream is exhausted (no more data events).
|
||||
*
|
||||
* @event GridFSBucketReadStream#end
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fired when the stream is exhausted and the underlying cursor is killed
|
||||
*
|
||||
* @event GridFSBucketReadStream#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reads from the cursor and pushes to the stream.
|
||||
* @method
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype._read = function() {
|
||||
var _this = this;
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
waitForFile(_this, function() {
|
||||
doRead(_this);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the 0-based offset in bytes to start streaming from. Throws
|
||||
* an error if this stream has entered flowing mode
|
||||
* (e.g. if you've already called `on('data')`)
|
||||
* @method
|
||||
* @param {Number} start Offset in bytes to start reading at
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.start = function(start) {
|
||||
throwIfInitialized(this);
|
||||
this.s.options.start = start;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the 0-based offset in bytes to start streaming from. Throws
|
||||
* an error if this stream has entered flowing mode
|
||||
* (e.g. if you've already called `on('data')`)
|
||||
* @method
|
||||
* @param {Number} end Offset in bytes to stop reading at
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.end = function(end) {
|
||||
throwIfInitialized(this);
|
||||
this.s.options.end = end;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks this stream as aborted (will never push another `data` event)
|
||||
* and kills the underlying cursor. Will emit the 'end' event, and then
|
||||
* the 'close' event once the cursor is successfully killed.
|
||||
*
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred.
|
||||
* @fires GridFSBucketWriteStream#close
|
||||
* @fires GridFSBucketWriteStream#end
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.abort = function(callback) {
|
||||
var _this = this;
|
||||
this.push(null);
|
||||
this.destroyed = true;
|
||||
if (this.s.cursor) {
|
||||
this.s.cursor.close(function(error) {
|
||||
_this.emit('close');
|
||||
callback && callback(error);
|
||||
});
|
||||
} else {
|
||||
if (!this.s.init) {
|
||||
// If not initialized, fire close event because we will never
|
||||
// get a cursor
|
||||
_this.emit('close');
|
||||
}
|
||||
callback && callback();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function throwIfInitialized(self) {
|
||||
if (self.s.init) {
|
||||
throw new Error('You cannot change options after the stream has entered' + 'flowing mode!');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function doRead(_this) {
|
||||
if (_this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this.s.cursor.next(function(error, doc) {
|
||||
if (_this.destroyed) {
|
||||
return;
|
||||
}
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
if (!doc) {
|
||||
_this.push(null);
|
||||
return _this.s.cursor.close(function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
_this.emit('close');
|
||||
});
|
||||
}
|
||||
|
||||
var bytesRemaining = _this.s.file.length - _this.s.bytesRead;
|
||||
var expectedN = _this.s.expected++;
|
||||
var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining);
|
||||
|
||||
if (doc.n > expectedN) {
|
||||
var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
if (doc.n < expectedN) {
|
||||
errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;
|
||||
|
||||
if (buf.length !== expectedLength) {
|
||||
if (bytesRemaining <= 0) {
|
||||
errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
errmsg =
|
||||
'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
_this.s.bytesRead += buf.length;
|
||||
|
||||
if (buf.length === 0) {
|
||||
return _this.push(null);
|
||||
}
|
||||
|
||||
var sliceStart = null;
|
||||
var sliceEnd = null;
|
||||
|
||||
if (_this.s.bytesToSkip != null) {
|
||||
sliceStart = _this.s.bytesToSkip;
|
||||
_this.s.bytesToSkip = 0;
|
||||
}
|
||||
|
||||
if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) {
|
||||
sliceEnd = _this.s.bytesToTrim;
|
||||
}
|
||||
|
||||
// If the remaining amount of data left is < chunkSize read the right amount of data
|
||||
if (_this.s.options.end && _this.s.options.end - _this.s.bytesToSkip < buf.length) {
|
||||
sliceEnd = _this.s.options.end - _this.s.bytesToSkip;
|
||||
}
|
||||
|
||||
if (sliceStart != null || sliceEnd != null) {
|
||||
buf = buf.slice(sliceStart || 0, sliceEnd || buf.length);
|
||||
}
|
||||
|
||||
_this.push(buf);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function init(self) {
|
||||
var findOneOptions = {};
|
||||
if (self.s.readPreference) {
|
||||
findOneOptions.readPreference = self.s.readPreference;
|
||||
}
|
||||
if (self.s.options && self.s.options.sort) {
|
||||
findOneOptions.sort = self.s.options.sort;
|
||||
}
|
||||
if (self.s.options && self.s.options.skip) {
|
||||
findOneOptions.skip = self.s.options.skip;
|
||||
}
|
||||
|
||||
self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) {
|
||||
if (error) {
|
||||
return __handleError(self, error);
|
||||
}
|
||||
if (!doc) {
|
||||
var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename;
|
||||
var errmsg = 'FileNotFound: file ' + identifier + ' was not found';
|
||||
var err = new Error(errmsg);
|
||||
err.code = 'ENOENT';
|
||||
return __handleError(self, err);
|
||||
}
|
||||
|
||||
// If document is empty, kill the stream immediately and don't
|
||||
// execute any reads
|
||||
if (doc.length <= 0) {
|
||||
self.push(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.destroyed) {
|
||||
// If user destroys the stream before we have a cursor, wait
|
||||
// until the query is done to say we're 'closed' because we can't
|
||||
// cancel a query.
|
||||
self.emit('close');
|
||||
return;
|
||||
}
|
||||
|
||||
self.s.bytesToSkip = handleStartOption(self, doc, self.s.options);
|
||||
|
||||
var filter = { files_id: doc._id };
|
||||
|
||||
// Currently (MongoDB 3.4.4) skip function does not support the index,
|
||||
// it needs to retrieve all the documents first and then skip them. (CS-25811)
|
||||
// As work around we use $gte on the "n" field.
|
||||
if (self.s.options && self.s.options.start != null) {
|
||||
var skip = Math.floor(self.s.options.start / doc.chunkSize);
|
||||
if (skip > 0) {
|
||||
filter['n'] = { $gte: skip };
|
||||
}
|
||||
}
|
||||
self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 });
|
||||
|
||||
if (self.s.readPreference) {
|
||||
self.s.cursor.setReadPreference(self.s.readPreference);
|
||||
}
|
||||
|
||||
self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
|
||||
self.s.file = doc;
|
||||
self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options);
|
||||
self.emit('file', doc);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function waitForFile(_this, callback) {
|
||||
if (_this.s.file) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
if (!_this.s.init) {
|
||||
init(_this);
|
||||
_this.s.init = true;
|
||||
}
|
||||
|
||||
_this.once('file', function() {
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function handleStartOption(stream, doc, options) {
|
||||
if (options && options.start != null) {
|
||||
if (options.start > doc.length) {
|
||||
throw new Error(
|
||||
'Stream start (' +
|
||||
options.start +
|
||||
') must not be ' +
|
||||
'more than the length of the file (' +
|
||||
doc.length +
|
||||
')'
|
||||
);
|
||||
}
|
||||
if (options.start < 0) {
|
||||
throw new Error('Stream start (' + options.start + ') must not be ' + 'negative');
|
||||
}
|
||||
if (options.end != null && options.end < options.start) {
|
||||
throw new Error(
|
||||
'Stream start (' +
|
||||
options.start +
|
||||
') must not be ' +
|
||||
'greater than stream end (' +
|
||||
options.end +
|
||||
')'
|
||||
);
|
||||
}
|
||||
|
||||
stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;
|
||||
stream.s.expected = Math.floor(options.start / doc.chunkSize);
|
||||
|
||||
return options.start - stream.s.bytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function handleEndOption(stream, doc, cursor, options) {
|
||||
if (options && options.end != null) {
|
||||
if (options.end > doc.length) {
|
||||
throw new Error(
|
||||
'Stream end (' +
|
||||
options.end +
|
||||
') must not be ' +
|
||||
'more than the length of the file (' +
|
||||
doc.length +
|
||||
')'
|
||||
);
|
||||
}
|
||||
if (options.start < 0) {
|
||||
throw new Error('Stream end (' + options.end + ') must not be ' + 'negative');
|
||||
}
|
||||
|
||||
var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;
|
||||
|
||||
cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
|
||||
|
||||
stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
|
||||
|
||||
return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function __handleError(_this, error) {
|
||||
_this.emit('error', error);
|
||||
}
|
358
node_modules/mongodb/lib/gridfs-stream/index.js
generated
vendored
Normal file
358
node_modules/mongodb/lib/gridfs-stream/index.js
generated
vendored
Normal file
@@ -0,0 +1,358 @@
|
||||
'use strict';
|
||||
|
||||
var Emitter = require('events').EventEmitter;
|
||||
var GridFSBucketReadStream = require('./download');
|
||||
var GridFSBucketWriteStream = require('./upload');
|
||||
var shallowClone = require('../utils').shallowClone;
|
||||
var toError = require('../utils').toError;
|
||||
var util = require('util');
|
||||
var executeOperation = require('../utils').executeOperation;
|
||||
|
||||
var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
|
||||
bucketName: 'fs',
|
||||
chunkSizeBytes: 255 * 1024
|
||||
};
|
||||
|
||||
module.exports = GridFSBucket;
|
||||
|
||||
/**
|
||||
* Constructor for a streaming GridFS interface
|
||||
* @class
|
||||
* @param {Db} db A db handle
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.
|
||||
* @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB
|
||||
* @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }`
|
||||
* @param {object} [options.readPreference] Optional read preference to be passed to read operations
|
||||
* @fires GridFSBucketWriteStream#index
|
||||
* @return {GridFSBucket}
|
||||
*/
|
||||
|
||||
function GridFSBucket(db, options) {
|
||||
Emitter.apply(this);
|
||||
this.setMaxListeners(0);
|
||||
|
||||
if (options && typeof options === 'object') {
|
||||
options = shallowClone(options);
|
||||
var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS);
|
||||
for (var i = 0; i < keys.length; ++i) {
|
||||
if (!options[keys[i]]) {
|
||||
options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
options = DEFAULT_GRIDFS_BUCKET_OPTIONS;
|
||||
}
|
||||
|
||||
this.s = {
|
||||
db: db,
|
||||
options: options,
|
||||
_chunksCollection: db.collection(options.bucketName + '.chunks'),
|
||||
_filesCollection: db.collection(options.bucketName + '.files'),
|
||||
checkedIndexes: false,
|
||||
calledOpenUploadStream: false,
|
||||
promiseLibrary: db.s.promiseLibrary || Promise
|
||||
};
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucket, Emitter);
|
||||
|
||||
/**
|
||||
* When the first call to openUploadStream is made, the upload stream will
|
||||
* check to see if it needs to create the proper indexes on the chunks and
|
||||
* files collections. This event is fired either when 1) it determines that
|
||||
* no index creation is necessary, 2) when it successfully creates the
|
||||
* necessary indexes.
|
||||
*
|
||||
* @event GridFSBucket#index
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns a writable stream (GridFSBucketWriteStream) for writing
|
||||
* buffers to GridFS. The stream's 'id' property contains the resulting
|
||||
* file's id.
|
||||
* @method
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
|
||||
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
|
||||
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
|
||||
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @return {GridFSBucketWriteStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openUploadStream = function(filename, options) {
|
||||
if (options) {
|
||||
options = shallowClone(options);
|
||||
} else {
|
||||
options = {};
|
||||
}
|
||||
if (!options.chunkSizeBytes) {
|
||||
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
|
||||
}
|
||||
return new GridFSBucketWriteStream(this, filename, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a writable stream (GridFSBucketWriteStream) for writing
|
||||
* buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
|
||||
* file's id.
|
||||
* @method
|
||||
* @param {string|number|object} id A custom id used to identify the file
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
|
||||
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
|
||||
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
|
||||
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @return {GridFSBucketWriteStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) {
|
||||
if (options) {
|
||||
options = shallowClone(options);
|
||||
} else {
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (!options.chunkSizeBytes) {
|
||||
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
|
||||
}
|
||||
|
||||
options.id = id;
|
||||
|
||||
return new GridFSBucketWriteStream(this, filename, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a readable stream (GridFSBucketReadStream) for streaming file
|
||||
* data from GridFS.
|
||||
* @method
|
||||
* @param {ObjectId} id The id of the file doc
|
||||
* @param {Object} [options] Optional settings.
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openDownloadStream = function(id, options) {
|
||||
var filter = { _id: id };
|
||||
options = {
|
||||
start: options && options.start,
|
||||
end: options && options.end
|
||||
};
|
||||
|
||||
return new GridFSBucketReadStream(
|
||||
this.s._chunksCollection,
|
||||
this.s._filesCollection,
|
||||
this.s.options.readPreference,
|
||||
filter,
|
||||
options
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a file with the given id
|
||||
* @method
|
||||
* @param {ObjectId} id The id of the file doc
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.delete = function(id, callback) {
|
||||
return executeOperation(this.s.db.s.topology, _delete, [this, id, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _delete(_this, id, callback) {
|
||||
_this.s._filesCollection.deleteOne({ _id: id }, function(error, res) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
_this.s._chunksCollection.deleteMany({ files_id: id }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
// Delete orphaned chunks before returning FileNotFound
|
||||
if (!res.result.n) {
|
||||
var errmsg = 'FileNotFound: no file with id ' + id + ' found';
|
||||
return callback(new Error(errmsg));
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper around find on the files collection
|
||||
* @method
|
||||
* @param {Object} filter
|
||||
* @param {Object} [options] Optional settings for cursor
|
||||
* @param {number} [options.batchSize] Optional batch size for cursor
|
||||
* @param {number} [options.limit] Optional limit for cursor
|
||||
* @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor
|
||||
* @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag
|
||||
* @param {number} [options.skip] Optional skip for cursor
|
||||
* @param {object} [options.sort] Optional sort for cursor
|
||||
* @return {Cursor}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.find = function(filter, options) {
|
||||
filter = filter || {};
|
||||
options = options || {};
|
||||
|
||||
var cursor = this.s._filesCollection.find(filter);
|
||||
|
||||
if (options.batchSize != null) {
|
||||
cursor.batchSize(options.batchSize);
|
||||
}
|
||||
if (options.limit != null) {
|
||||
cursor.limit(options.limit);
|
||||
}
|
||||
if (options.maxTimeMS != null) {
|
||||
cursor.maxTimeMS(options.maxTimeMS);
|
||||
}
|
||||
if (options.noCursorTimeout != null) {
|
||||
cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout);
|
||||
}
|
||||
if (options.skip != null) {
|
||||
cursor.skip(options.skip);
|
||||
}
|
||||
if (options.sort != null) {
|
||||
cursor.sort(options.sort);
|
||||
}
|
||||
|
||||
return cursor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a readable stream (GridFSBucketReadStream) for streaming the
|
||||
* file with the given name from GridFS. If there are multiple files with
|
||||
* the same name, this will stream the most recent file with the given name
|
||||
* (as determined by the `uploadDate` field). You can set the `revision`
|
||||
* option to change this behavior.
|
||||
* @method
|
||||
* @param {String} filename The name of the file to stream
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest.
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) {
|
||||
var sort = { uploadDate: -1 };
|
||||
var skip = null;
|
||||
if (options && options.revision != null) {
|
||||
if (options.revision >= 0) {
|
||||
sort = { uploadDate: 1 };
|
||||
skip = options.revision;
|
||||
} else {
|
||||
skip = -options.revision - 1;
|
||||
}
|
||||
}
|
||||
|
||||
var filter = { filename: filename };
|
||||
options = {
|
||||
sort: sort,
|
||||
skip: skip,
|
||||
start: options && options.start,
|
||||
end: options && options.end
|
||||
};
|
||||
return new GridFSBucketReadStream(
|
||||
this.s._chunksCollection,
|
||||
this.s._filesCollection,
|
||||
this.s.options.readPreference,
|
||||
filter,
|
||||
options
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Renames the file with the given _id to the given string
|
||||
* @method
|
||||
* @param {ObjectId} id the id of the file to rename
|
||||
* @param {String} filename new name for the file
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.rename = function(id, filename, callback) {
|
||||
return executeOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _rename(_this, id, filename, callback) {
|
||||
var filter = { _id: id };
|
||||
var update = { $set: { filename: filename } };
|
||||
_this.s._filesCollection.updateOne(filter, update, function(error, res) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
if (!res.result.n) {
|
||||
return callback(toError('File with id ' + id + ' not found'));
|
||||
}
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes this bucket's files collection, followed by its chunks collection.
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.drop = function(callback) {
|
||||
return executeOperation(this.s.db.s.topology, _drop, [this, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the db logger
|
||||
* @method
|
||||
* @return {Logger} return the db logger
|
||||
* @ignore
|
||||
*/
|
||||
GridFSBucket.prototype.getLogger = function() {
|
||||
return this.s.db.s.logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _drop(_this, callback) {
|
||||
_this.s._filesCollection.drop(function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
_this.s._chunksCollection.drop(function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
return callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback format for all GridFSBucket methods that can accept a callback.
|
||||
* @callback GridFSBucket~errorCallback
|
||||
* @param {MongoError} error An error instance representing any errors that occurred
|
||||
*/
|
538
node_modules/mongodb/lib/gridfs-stream/upload.js
generated
vendored
Normal file
538
node_modules/mongodb/lib/gridfs-stream/upload.js
generated
vendored
Normal file
@@ -0,0 +1,538 @@
|
||||
'use strict';
|
||||
|
||||
var core = require('mongodb-core');
|
||||
var crypto = require('crypto');
|
||||
var stream = require('stream');
|
||||
var util = require('util');
|
||||
var Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
var ERROR_NAMESPACE_NOT_FOUND = 26;
|
||||
|
||||
module.exports = GridFSBucketWriteStream;
|
||||
|
||||
/**
|
||||
* A writable stream that enables you to write buffers to GridFS.
|
||||
*
|
||||
* Do not instantiate this class directly. Use `openUploadStream()` instead.
|
||||
*
|
||||
* @class
|
||||
* @param {GridFSBucket} bucket Handle for this stream's corresponding bucket
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string|number|object} [options.id] Custom file id for the GridFS file.
|
||||
* @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes
|
||||
* @param {number} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {number} [options.j] The journal write concern
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @fires GridFSBucketWriteStream#error
|
||||
* @fires GridFSBucketWriteStream#finish
|
||||
* @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance.
|
||||
*/
|
||||
|
||||
function GridFSBucketWriteStream(bucket, filename, options) {
|
||||
options = options || {};
|
||||
this.bucket = bucket;
|
||||
this.chunks = bucket.s._chunksCollection;
|
||||
this.filename = filename;
|
||||
this.files = bucket.s._filesCollection;
|
||||
this.options = options;
|
||||
// Signals the write is all done
|
||||
this.done = false;
|
||||
|
||||
this.id = options.id ? options.id : core.BSON.ObjectId();
|
||||
this.chunkSizeBytes = this.options.chunkSizeBytes;
|
||||
this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
|
||||
this.length = 0;
|
||||
this.md5 = !options.disableMD5 && crypto.createHash('md5');
|
||||
this.n = 0;
|
||||
this.pos = 0;
|
||||
this.state = {
|
||||
streamEnd: false,
|
||||
outstandingRequests: 0,
|
||||
errored: false,
|
||||
aborted: false,
|
||||
promiseLibrary: this.bucket.s.promiseLibrary
|
||||
};
|
||||
|
||||
if (!this.bucket.s.calledOpenUploadStream) {
|
||||
this.bucket.s.calledOpenUploadStream = true;
|
||||
|
||||
var _this = this;
|
||||
checkIndexes(this, function() {
|
||||
_this.bucket.s.checkedIndexes = true;
|
||||
_this.bucket.emit('index');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucketWriteStream, stream.Writable);
|
||||
|
||||
/**
|
||||
* An error occurred
|
||||
*
|
||||
* @event GridFSBucketWriteStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* `end()` was called and the write stream successfully wrote the file
|
||||
* metadata and all the chunks to MongoDB.
|
||||
*
|
||||
* @event GridFSBucketWriteStream#finish
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Write a buffer to the stream.
|
||||
*
|
||||
* @method
|
||||
* @param {Buffer} chunk Buffer to write
|
||||
* @param {String} encoding Optional encoding for the buffer
|
||||
* @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
|
||||
* @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise.
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) {
|
||||
var _this = this;
|
||||
return waitForIndexes(this, function() {
|
||||
return doWrite(_this, chunk, encoding, callback);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Places this write stream into an aborted state (all future writes fail)
|
||||
* and deletes all chunks that have already been written.
|
||||
*
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred
|
||||
* @return {Promise} if no callback specified
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.abort = function(callback) {
|
||||
if (this.state.streamEnd) {
|
||||
var error = new Error('Cannot abort a stream that has already completed');
|
||||
if (typeof callback === 'function') {
|
||||
return callback(error);
|
||||
}
|
||||
return this.state.promiseLibrary.reject(error);
|
||||
}
|
||||
if (this.state.aborted) {
|
||||
error = new Error('Cannot call abort() on a stream twice');
|
||||
if (typeof callback === 'function') {
|
||||
return callback(error);
|
||||
}
|
||||
return this.state.promiseLibrary.reject(error);
|
||||
}
|
||||
this.state.aborted = true;
|
||||
this.chunks.deleteMany({ files_id: this.id }, function(error) {
|
||||
if (typeof callback === 'function') callback(error);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Tells the stream that no more data will be coming in. The stream will
|
||||
* persist the remaining data to MongoDB, write the files document, and
|
||||
* then emit a 'finish' event.
|
||||
*
|
||||
* @method
|
||||
* @param {Buffer} chunk Buffer to write
|
||||
* @param {String} encoding Optional encoding for the buffer
|
||||
* @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) {
|
||||
var _this = this;
|
||||
if (typeof chunk === 'function') {
|
||||
(callback = chunk), (chunk = null), (encoding = null);
|
||||
} else if (typeof encoding === 'function') {
|
||||
(callback = encoding), (encoding = null);
|
||||
}
|
||||
|
||||
if (checkAborted(this, callback)) {
|
||||
return;
|
||||
}
|
||||
this.state.streamEnd = true;
|
||||
|
||||
if (callback) {
|
||||
this.once('finish', function(result) {
|
||||
callback(null, result);
|
||||
});
|
||||
}
|
||||
|
||||
if (!chunk) {
|
||||
waitForIndexes(this, function() {
|
||||
writeRemnant(_this);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.write(chunk, encoding, function() {
|
||||
writeRemnant(_this);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function __handleError(_this, error, callback) {
|
||||
if (_this.state.errored) {
|
||||
return;
|
||||
}
|
||||
_this.state.errored = true;
|
||||
if (callback) {
|
||||
return callback(error);
|
||||
}
|
||||
_this.emit('error', error);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function createChunkDoc(filesId, n, data) {
|
||||
return {
|
||||
_id: core.BSON.ObjectId(),
|
||||
files_id: filesId,
|
||||
n: n,
|
||||
data: data
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkChunksIndex(_this, callback) {
|
||||
_this.chunks.listIndexes().toArray(function(error, indexes) {
|
||||
if (error) {
|
||||
// Collection doesn't exist so create index
|
||||
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
|
||||
var index = { files_id: 1, n: 1 };
|
||||
_this.chunks.createIndex(index, { background: false, unique: true }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
return;
|
||||
}
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
var hasChunksIndex = false;
|
||||
indexes.forEach(function(index) {
|
||||
if (index.key) {
|
||||
var keys = Object.keys(index.key);
|
||||
if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
|
||||
hasChunksIndex = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (hasChunksIndex) {
|
||||
callback();
|
||||
} else {
|
||||
index = { files_id: 1, n: 1 };
|
||||
var indexOptions = getWriteOptions(_this);
|
||||
|
||||
indexOptions.background = false;
|
||||
indexOptions.unique = true;
|
||||
|
||||
_this.chunks.createIndex(index, indexOptions, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkDone(_this, callback) {
|
||||
if (_this.done) return true;
|
||||
if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) {
|
||||
// Set done so we dont' trigger duplicate createFilesDoc
|
||||
_this.done = true;
|
||||
// Create a new files doc
|
||||
var filesDoc = createFilesDoc(
|
||||
_this.id,
|
||||
_this.length,
|
||||
_this.chunkSizeBytes,
|
||||
_this.md5 && _this.md5.digest('hex'),
|
||||
_this.filename,
|
||||
_this.options.contentType,
|
||||
_this.options.aliases,
|
||||
_this.options.metadata
|
||||
);
|
||||
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error, callback);
|
||||
}
|
||||
_this.emit('finish', filesDoc);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkIndexes(_this, callback) {
|
||||
_this.files.findOne({}, { _id: 1 }, function(error, doc) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
if (doc) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
_this.files.listIndexes().toArray(function(error, indexes) {
|
||||
if (error) {
|
||||
// Collection doesn't exist so create index
|
||||
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
|
||||
var index = { filename: 1, uploadDate: 1 };
|
||||
_this.files.createIndex(index, { background: false }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
checkChunksIndex(_this, callback);
|
||||
});
|
||||
return;
|
||||
}
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
var hasFileIndex = false;
|
||||
indexes.forEach(function(index) {
|
||||
var keys = Object.keys(index.key);
|
||||
if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
|
||||
hasFileIndex = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (hasFileIndex) {
|
||||
checkChunksIndex(_this, callback);
|
||||
} else {
|
||||
index = { filename: 1, uploadDate: 1 };
|
||||
|
||||
var indexOptions = getWriteOptions(_this);
|
||||
|
||||
indexOptions.background = false;
|
||||
|
||||
_this.files.createIndex(index, indexOptions, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
checkChunksIndex(_this, callback);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) {
|
||||
var ret = {
|
||||
_id: _id,
|
||||
length: length,
|
||||
chunkSize: chunkSize,
|
||||
uploadDate: new Date(),
|
||||
filename: filename
|
||||
};
|
||||
|
||||
if (md5) {
|
||||
ret.md5 = md5;
|
||||
}
|
||||
|
||||
if (contentType) {
|
||||
ret.contentType = contentType;
|
||||
}
|
||||
|
||||
if (aliases) {
|
||||
ret.aliases = aliases;
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
ret.metadata = metadata;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function doWrite(_this, chunk, encoding, callback) {
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
|
||||
|
||||
_this.length += inputBuf.length;
|
||||
|
||||
// Input is small enough to fit in our buffer
|
||||
if (_this.pos + inputBuf.length < _this.chunkSizeBytes) {
|
||||
inputBuf.copy(_this.bufToStore, _this.pos);
|
||||
_this.pos += inputBuf.length;
|
||||
|
||||
callback && callback();
|
||||
|
||||
// Note that we reverse the typical semantics of write's return value
|
||||
// to be compatible with node's `.pipe()` function.
|
||||
// True means client can keep writing.
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise, buffer is too big for current chunk, so we need to flush
|
||||
// to MongoDB.
|
||||
var inputBufRemaining = inputBuf.length;
|
||||
var spaceRemaining = _this.chunkSizeBytes - _this.pos;
|
||||
var numToCopy = Math.min(spaceRemaining, inputBuf.length);
|
||||
var outstandingRequests = 0;
|
||||
while (inputBufRemaining > 0) {
|
||||
var inputBufPos = inputBuf.length - inputBufRemaining;
|
||||
inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy);
|
||||
_this.pos += numToCopy;
|
||||
spaceRemaining -= numToCopy;
|
||||
if (spaceRemaining === 0) {
|
||||
if (_this.md5) {
|
||||
_this.md5.update(_this.bufToStore);
|
||||
}
|
||||
var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore);
|
||||
++_this.state.outstandingRequests;
|
||||
++outstandingRequests;
|
||||
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
--_this.state.outstandingRequests;
|
||||
--outstandingRequests;
|
||||
|
||||
if (!outstandingRequests) {
|
||||
_this.emit('drain', doc);
|
||||
callback && callback();
|
||||
checkDone(_this);
|
||||
}
|
||||
});
|
||||
|
||||
spaceRemaining = _this.chunkSizeBytes;
|
||||
_this.pos = 0;
|
||||
++_this.n;
|
||||
}
|
||||
inputBufRemaining -= numToCopy;
|
||||
numToCopy = Math.min(spaceRemaining, inputBufRemaining);
|
||||
}
|
||||
|
||||
// Note that we reverse the typical semantics of write's return value
|
||||
// to be compatible with node's `.pipe()` function.
|
||||
// False means the client should wait for the 'drain' event.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function getWriteOptions(_this) {
|
||||
var obj = {};
|
||||
if (_this.options.writeConcern) {
|
||||
obj.w = _this.options.writeConcern.w;
|
||||
obj.wtimeout = _this.options.writeConcern.wtimeout;
|
||||
obj.j = _this.options.writeConcern.j;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function waitForIndexes(_this, callback) {
|
||||
if (_this.bucket.s.checkedIndexes) {
|
||||
return callback(false);
|
||||
}
|
||||
|
||||
_this.bucket.once('index', function() {
|
||||
callback(true);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function writeRemnant(_this, callback) {
|
||||
// Buffer is empty, so don't bother to insert
|
||||
if (_this.pos === 0) {
|
||||
return checkDone(_this, callback);
|
||||
}
|
||||
|
||||
++_this.state.outstandingRequests;
|
||||
|
||||
// Create a new buffer to make sure the buffer isn't bigger than it needs
|
||||
// to be.
|
||||
var remnant = Buffer.alloc(_this.pos);
|
||||
_this.bufToStore.copy(remnant, 0, 0, _this.pos);
|
||||
if (_this.md5) {
|
||||
_this.md5.update(remnant);
|
||||
}
|
||||
var doc = createChunkDoc(_this.id, _this.n, remnant);
|
||||
|
||||
// If the stream was aborted, do not write remnant
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
--_this.state.outstandingRequests;
|
||||
checkDone(_this);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkAborted(_this, callback) {
|
||||
if (_this.state.aborted) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(new Error('this stream has been aborted'));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
236
node_modules/mongodb/lib/gridfs/chunk.js
generated
vendored
Normal file
236
node_modules/mongodb/lib/gridfs/chunk.js
generated
vendored
Normal file
@@ -0,0 +1,236 @@
|
||||
'use strict';
|
||||
|
||||
var Binary = require('mongodb-core').BSON.Binary,
|
||||
ObjectID = require('mongodb-core').BSON.ObjectID;
|
||||
|
||||
var Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
/**
|
||||
* Class for representing a single chunk in GridFS.
|
||||
*
|
||||
* @class
|
||||
*
|
||||
* @param file {GridStore} The {@link GridStore} object holding this chunk.
|
||||
* @param mongoObject {object} The mongo object representation of this chunk.
|
||||
*
|
||||
* @throws Error when the type of data field for {@link mongoObject} is not
|
||||
* supported. Currently supported types for data field are instances of
|
||||
* {@link String}, {@link Array}, {@link Binary} and {@link Binary}
|
||||
* from the bson module
|
||||
*
|
||||
* @see Chunk#buildMongoObject
|
||||
*/
|
||||
var Chunk = function(file, mongoObject, writeConcern) {
|
||||
if (!(this instanceof Chunk)) return new Chunk(file, mongoObject);
|
||||
|
||||
this.file = file;
|
||||
var mongoObjectFinal = mongoObject == null ? {} : mongoObject;
|
||||
this.writeConcern = writeConcern || { w: 1 };
|
||||
this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;
|
||||
this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;
|
||||
this.data = new Binary();
|
||||
|
||||
if (typeof mongoObjectFinal.data === 'string') {
|
||||
var buffer = Buffer.alloc(mongoObjectFinal.data.length);
|
||||
buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary');
|
||||
this.data = new Binary(buffer);
|
||||
} else if (Array.isArray(mongoObjectFinal.data)) {
|
||||
buffer = Buffer.alloc(mongoObjectFinal.data.length);
|
||||
var data = mongoObjectFinal.data.join('');
|
||||
buffer.write(data, 0, data.length, 'binary');
|
||||
this.data = new Binary(buffer);
|
||||
} else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') {
|
||||
this.data = mongoObjectFinal.data;
|
||||
} else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) {
|
||||
throw Error('Illegal chunk format');
|
||||
}
|
||||
|
||||
// Update position
|
||||
this.internalPosition = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a data to this object and advance the read/write head.
|
||||
*
|
||||
* @param data {string} the data to write
|
||||
* @param callback {function(*, GridStore)} This will be called after executing
|
||||
* this method. The first parameter will contain null and the second one
|
||||
* will contain a reference to this object.
|
||||
*/
|
||||
Chunk.prototype.write = function(data, callback) {
|
||||
this.data.write(data, this.internalPosition, data.length, 'binary');
|
||||
this.internalPosition = this.data.length();
|
||||
if (callback != null) return callback(null, this);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads data and advances the read/write head.
|
||||
*
|
||||
* @param length {number} The length of data to read.
|
||||
*
|
||||
* @return {string} The data read if the given length will not exceed the end of
|
||||
* the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.read = function(length) {
|
||||
// Default to full read if no index defined
|
||||
length = length == null || length === 0 ? this.length() : length;
|
||||
|
||||
if (this.length() - this.internalPosition + 1 >= length) {
|
||||
var data = this.data.read(this.internalPosition, length);
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
Chunk.prototype.readSlice = function(length) {
|
||||
if (this.length() - this.internalPosition >= length) {
|
||||
var data = null;
|
||||
if (this.data.buffer != null) {
|
||||
//Pure BSON
|
||||
data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);
|
||||
} else {
|
||||
//Native BSON
|
||||
data = Buffer.alloc(length);
|
||||
length = this.data.readInto(data, this.internalPosition);
|
||||
}
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the read/write head is at the end.
|
||||
*
|
||||
* @return {boolean} Whether the read/write head has reached the end of this
|
||||
* chunk.
|
||||
*/
|
||||
Chunk.prototype.eof = function() {
|
||||
return this.internalPosition === this.length() ? true : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads one character from the data of this chunk and advances the read/write
|
||||
* head.
|
||||
*
|
||||
* @return {string} a single character data read if the the read/write head is
|
||||
* not at the end of the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.getc = function() {
|
||||
return this.read(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clears the contents of the data in this chunk and resets the read/write head
|
||||
* to the initial position.
|
||||
*/
|
||||
Chunk.prototype.rewind = function() {
|
||||
this.internalPosition = 0;
|
||||
this.data = new Binary();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves this chunk to the database. Also overwrites existing entries having the
|
||||
* same id as this chunk.
|
||||
*
|
||||
* @param callback {function(*, GridStore)} This will be called after executing
|
||||
* this method. The first parameter will contain null and the second one
|
||||
* will contain a reference to this object.
|
||||
*/
|
||||
Chunk.prototype.save = function(options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
self.file.chunkCollection(function(err, collection) {
|
||||
if (err) return callback(err);
|
||||
|
||||
// Merge the options
|
||||
var writeOptions = { upsert: true };
|
||||
for (var name in options) writeOptions[name] = options[name];
|
||||
for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name];
|
||||
|
||||
if (self.data.length() > 0) {
|
||||
self.buildMongoObject(function(mongoObject) {
|
||||
var options = { forceServerObjectId: true };
|
||||
for (var name in self.writeConcern) {
|
||||
options[name] = self.writeConcern[name];
|
||||
}
|
||||
|
||||
collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) {
|
||||
callback(err, self);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
callback(null, self);
|
||||
}
|
||||
// });
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a mongoDB object representation of this chunk.
|
||||
*
|
||||
* @param callback {function(Object)} This will be called after executing this
|
||||
* method. The object will be passed to the first parameter and will have
|
||||
* the structure:
|
||||
*
|
||||
* <pre><code>
|
||||
* {
|
||||
* '_id' : , // {number} id for this chunk
|
||||
* 'files_id' : , // {number} foreign key to the file collection
|
||||
* 'n' : , // {number} chunk number
|
||||
* 'data' : , // {bson#Binary} the chunk data itself
|
||||
* }
|
||||
* </code></pre>
|
||||
*
|
||||
* @see <a href="http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}">MongoDB GridFS Chunk Object Structure</a>
|
||||
*/
|
||||
Chunk.prototype.buildMongoObject = function(callback) {
|
||||
var mongoObject = {
|
||||
files_id: this.file.fileId,
|
||||
n: this.chunkNumber,
|
||||
data: this.data
|
||||
};
|
||||
// If we are saving using a specific ObjectId
|
||||
if (this.objectId != null) mongoObject._id = this.objectId;
|
||||
|
||||
callback(mongoObject);
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {number} the length of the data
|
||||
*/
|
||||
Chunk.prototype.length = function() {
|
||||
return this.data.length();
|
||||
};
|
||||
|
||||
/**
|
||||
* The position of the read/write head
|
||||
* @name position
|
||||
* @lends Chunk#
|
||||
* @field
|
||||
*/
|
||||
Object.defineProperty(Chunk.prototype, 'position', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.internalPosition;
|
||||
},
|
||||
set: function(value) {
|
||||
this.internalPosition = value;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The default chunk size
|
||||
* @constant
|
||||
*/
|
||||
Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255;
|
||||
|
||||
module.exports = Chunk;
|
1907
node_modules/mongodb/lib/gridfs/grid_store.js
generated
vendored
Normal file
1907
node_modules/mongodb/lib/gridfs/grid_store.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
472
node_modules/mongodb/lib/mongo_client.js
generated
vendored
Normal file
472
node_modules/mongodb/lib/mongo_client.js
generated
vendored
Normal file
@@ -0,0 +1,472 @@
|
||||
'use strict';
|
||||
|
||||
const ChangeStream = require('./change_stream');
|
||||
const Db = require('./db');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const executeOperation = require('./utils').executeOperation;
|
||||
const handleCallback = require('./utils').handleCallback;
|
||||
const inherits = require('util').inherits;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
|
||||
// Operations
|
||||
const connectOp = require('./operations/mongo_client_ops').connectOp;
|
||||
const logout = require('./operations/mongo_client_ops').logout;
|
||||
const validOptions = require('./operations/mongo_client_ops').validOptions;
|
||||
|
||||
/**
|
||||
* @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB.
|
||||
*
|
||||
* @example
|
||||
* // Connect using a MongoClient instance
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* const mongoClient = new MongoClient(url);
|
||||
* mongoClient.connect(function(err, client) {
|
||||
* const db = client.db(dbName);
|
||||
* client.close();
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Connect using the MongoClient.connect static method
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* const db = client.db(dbName);
|
||||
* client.close();
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new MongoClient instance
|
||||
* @class
|
||||
* @param {string} url The connection URI string
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {number} [options.poolSize=5] The maximum size of the individual server pool
|
||||
* @param {boolean} [options.ssl=false] Enable SSL connection.
|
||||
* @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority
|
||||
* @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer
|
||||
* @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer
|
||||
* @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer
|
||||
* @param {string} [options.sslPass=undefined] SSL Certificate pass phrase
|
||||
* @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer
|
||||
* @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
|
||||
* @param {boolean} [options.noDelay=true] TCP Connection no delay
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting
|
||||
* @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
|
||||
* If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
|
||||
* @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
|
||||
* @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
|
||||
* @param {string} [options.replicaSet=undefined] The Replicaset set name
|
||||
* @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
|
||||
* @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
|
||||
* @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
|
||||
* @param {string} [options.authSource=undefined] Define the database to authenticate against
|
||||
* @param {(number|string)} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern
|
||||
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers
|
||||
* @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
|
||||
* @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
|
||||
* @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
|
||||
* @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
|
||||
* @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
|
||||
* @param {object} [options.logger=undefined] Custom logger object
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
|
||||
* @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function
|
||||
* @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
|
||||
* @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
|
||||
* @param {string} [options.auth.user=undefined] The username for auth
|
||||
* @param {string} [options.auth.password=undefined] The password for auth
|
||||
* @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1
|
||||
* @param {object} [options.compression] Type of compression to use: snappy or zlib
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern
|
||||
* @param {array} [options.readPreferenceTags] Read preference tags
|
||||
* @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
|
||||
* @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
|
||||
* @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
|
||||
* @param {boolean} [options.useNewUrlParser=false] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future.
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {MongoClient} a MongoClient instance
|
||||
*/
|
||||
function MongoClient(url, options) {
|
||||
if (!(this instanceof MongoClient)) return new MongoClient(url, options);
|
||||
// Set up event emitter
|
||||
EventEmitter.call(this);
|
||||
|
||||
// The internal state
|
||||
this.s = {
|
||||
url: url,
|
||||
options: options || {},
|
||||
promiseLibrary: null,
|
||||
dbCache: {},
|
||||
sessions: []
|
||||
};
|
||||
|
||||
// Get the promiseLibrary
|
||||
const promiseLibrary = this.s.options.promiseLibrary || Promise;
|
||||
|
||||
// Add the promise to the internal state
|
||||
this.s.promiseLibrary = promiseLibrary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(MongoClient, EventEmitter);
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback MongoClient~connectCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {MongoClient} client The connected client.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {Promise<MongoClient>} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.prototype.connect = function(callback) {
|
||||
// Validate options object
|
||||
const err = validOptions(this.s.options);
|
||||
|
||||
if (typeof callback === 'string') {
|
||||
throw new TypeError('`connect` only accepts a callback');
|
||||
}
|
||||
|
||||
return executeOperation(this, connectOp, [this, err, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Logout user from server, fire off on all connections and remove all auth info
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string} [options.dbName] Logout against different database than current.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.prototype.logout = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
// Establish the correct database name
|
||||
const dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName;
|
||||
|
||||
return executeOperation(this, logout, [this, dbName, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Close the db and its underlying connections
|
||||
* @method
|
||||
* @param {boolean} force Force close, emitting no events
|
||||
* @param {Db~noResultCallback} [callback] The result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.prototype.close = function(force, callback) {
|
||||
if (typeof force === 'function') (callback = force), (force = false);
|
||||
|
||||
// Close the topology connection
|
||||
if (this.topology) {
|
||||
this.topology.close(force);
|
||||
}
|
||||
// Emit close event
|
||||
this.emit('close', this);
|
||||
|
||||
// Fire close event on any cached db instances
|
||||
for (const name in this.s.dbCache) {
|
||||
this.s.dbCache[name].emit('close');
|
||||
}
|
||||
|
||||
// Remove listeners after emit
|
||||
this.removeAllListeners('close');
|
||||
|
||||
// Callback after next event loop tick
|
||||
if (typeof callback === 'function')
|
||||
return process.nextTick(() => {
|
||||
handleCallback(callback, null);
|
||||
});
|
||||
|
||||
// Return dummy promise
|
||||
return new this.s.promiseLibrary(resolve => {
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
|
||||
* related in a parent-child relationship to the original instance so that events are correctly emitted on child
|
||||
* db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
|
||||
* You can control these behaviors with the options noListener and returnNonCachedInstance.
|
||||
*
|
||||
* @method
|
||||
* @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
|
||||
* @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
|
||||
* @return {Db}
|
||||
*/
|
||||
MongoClient.prototype.db = function(dbName, options) {
|
||||
options = options || {};
|
||||
|
||||
// Default to db from connection string if not provided
|
||||
if (!dbName) {
|
||||
dbName = this.s.options.dbName;
|
||||
}
|
||||
|
||||
// Copy the options and add out internal override of the not shared flag
|
||||
const finalOptions = Object.assign({}, this.s.options, options);
|
||||
|
||||
// Do we have the db in the cache already
|
||||
if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) {
|
||||
return this.s.dbCache[dbName];
|
||||
}
|
||||
|
||||
// Add promiseLibrary
|
||||
finalOptions.promiseLibrary = this.s.promiseLibrary;
|
||||
|
||||
// If no topology throw an error message
|
||||
if (!this.topology) {
|
||||
throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
|
||||
}
|
||||
|
||||
// Return the db object
|
||||
const db = new Db(dbName, this.topology, finalOptions);
|
||||
|
||||
// Add the db to the cache
|
||||
this.s.dbCache[dbName] = db;
|
||||
// Return the database
|
||||
return db;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if MongoClient is connected
|
||||
*
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
|
||||
* @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
|
||||
* @return {boolean}
|
||||
*/
|
||||
MongoClient.prototype.isConnected = function(options) {
|
||||
options = options || {};
|
||||
|
||||
if (!this.topology) return false;
|
||||
return this.topology.isConnected(options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @static
|
||||
* @param {string} url The connection URI string
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {number} [options.poolSize=5] The maximum size of the individual server pool
|
||||
* @param {boolean} [options.ssl=false] Enable SSL connection.
|
||||
* @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority
|
||||
* @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer
|
||||
* @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer
|
||||
* @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer
|
||||
* @param {string} [options.sslPass=undefined] SSL Certificate pass phrase
|
||||
* @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer
|
||||
* @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
|
||||
* @param {boolean} [options.noDelay=true] TCP Connection no delay
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting
|
||||
* @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
|
||||
* If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
|
||||
* @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
|
||||
* @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
|
||||
* @param {string} [options.replicaSet=undefined] The Replicaset set name
|
||||
* @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
|
||||
* @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
|
||||
* @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
|
||||
* @param {string} [options.authSource=undefined] Define the database to authenticate against
|
||||
* @param {(number|string)} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern
|
||||
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers
|
||||
* @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
|
||||
* @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
|
||||
* @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
|
||||
* @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
|
||||
* @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
|
||||
* @param {object} [options.logger=undefined] Custom logger object
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
|
||||
* @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function
|
||||
* @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
|
||||
* @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
|
||||
* @param {string} [options.auth.user=undefined] The username for auth
|
||||
* @param {string} [options.auth.password=undefined] The password for auth
|
||||
* @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1
|
||||
* @param {object} [options.compression] Type of compression to use: snappy or zlib
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern
|
||||
* @param {array} [options.readPreferenceTags] Read preference tags
|
||||
* @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
|
||||
* @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
|
||||
* @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {Promise<MongoClient>} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.connect = function(url, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
options = args.length ? args.shift() : null;
|
||||
options = options || {};
|
||||
|
||||
// Create client
|
||||
const mongoClient = new MongoClient(url, options);
|
||||
// Execute the connect method
|
||||
return mongoClient.connect(callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts a new session on the server
|
||||
*
|
||||
* @param {SessionOptions} [options] optional settings for a driver session
|
||||
* @return {ClientSession} the newly established session
|
||||
*/
|
||||
MongoClient.prototype.startSession = function(options) {
|
||||
options = Object.assign({ explicit: true }, options);
|
||||
if (!this.topology) {
|
||||
throw new MongoError('Must connect to a server before calling this method');
|
||||
}
|
||||
|
||||
if (!this.topology.hasSessionSupport()) {
|
||||
throw new MongoError('Current topology does not support sessions');
|
||||
}
|
||||
|
||||
return this.topology.startSession(options, this.s.options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs a given operation with an implicitly created session. The lifetime of the session
|
||||
* will be handled without the need for user interaction.
|
||||
*
|
||||
* NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)
|
||||
*
|
||||
* @param {Object} [options] Optional settings to be appled to implicitly created session
|
||||
* @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}`
|
||||
* @return {Promise}
|
||||
*/
|
||||
MongoClient.prototype.withSession = function(options, operation) {
|
||||
if (typeof options === 'function') (operation = options), (options = undefined);
|
||||
const session = this.startSession(options);
|
||||
|
||||
let cleanupHandler = (err, result, opts) => {
|
||||
// prevent multiple calls to cleanupHandler
|
||||
cleanupHandler = () => {
|
||||
throw new ReferenceError('cleanupHandler was called too many times');
|
||||
};
|
||||
|
||||
opts = Object.assign({ throw: true }, opts);
|
||||
session.endSession();
|
||||
|
||||
if (err) {
|
||||
if (opts.throw) throw err;
|
||||
return Promise.reject(err);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const result = operation(session);
|
||||
return Promise.resolve(result)
|
||||
.then(result => cleanupHandler(null, result))
|
||||
.catch(err => cleanupHandler(err, null, { throw: true }));
|
||||
} catch (err) {
|
||||
return cleanupHandler(err, null, { throw: false });
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin,
|
||||
* and config databases.
|
||||
* @method
|
||||
* @since 3.1.0
|
||||
* @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
|
||||
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
|
||||
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
|
||||
* @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
|
||||
* @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @return {ChangeStream} a ChangeStream instance.
|
||||
*/
|
||||
MongoClient.prototype.watch = function(pipeline, options) {
|
||||
pipeline = pipeline || [];
|
||||
options = options || {};
|
||||
|
||||
// Allow optionally not specifying a pipeline
|
||||
if (!Array.isArray(pipeline)) {
|
||||
options = pipeline;
|
||||
pipeline = [];
|
||||
}
|
||||
|
||||
return new ChangeStream(this, pipeline, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the mongo client logger
|
||||
* @method
|
||||
* @return {Logger} return the mongo client logger
|
||||
* @ignore
|
||||
*/
|
||||
MongoClient.prototype.getLogger = function() {
|
||||
return this.s.options.logger;
|
||||
};
|
||||
|
||||
module.exports = MongoClient;
|
62
node_modules/mongodb/lib/operations/admin_ops.js
generated
vendored
Normal file
62
node_modules/mongodb/lib/operations/admin_ops.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
'use strict';
|
||||
|
||||
const executeCommand = require('./db_ops').executeCommand;
|
||||
const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand;
|
||||
|
||||
/**
|
||||
* Get ReplicaSet status
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
*/
|
||||
function replSetGetStatus(admin, options, callback) {
|
||||
executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve this db's server status.
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function serverStatus(admin, options, callback) {
|
||||
executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an existing collection
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {string} collectionName The name of the collection to validate.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
*/
|
||||
function validateCollection(admin, collectionName, options, callback) {
|
||||
const command = { validate: collectionName };
|
||||
const keys = Object.keys(options);
|
||||
|
||||
// Decorate command with extra options
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') {
|
||||
command[keys[i]] = options[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
executeCommand(admin.s.db, command, options, (err, doc) => {
|
||||
if (err != null) return callback(err, null);
|
||||
|
||||
if (doc.ok === 0) return callback(new Error('Error with validate command'), null);
|
||||
if (doc.result != null && doc.result.constructor !== String)
|
||||
return callback(new Error('Error with validation data'), null);
|
||||
if (doc.result != null && doc.result.match(/exception|corrupt/) != null)
|
||||
return callback(new Error('Error: invalid collection ' + collectionName), null);
|
||||
if (doc.valid != null && !doc.valid)
|
||||
return callback(new Error('Error: invalid collection ' + collectionName), null);
|
||||
|
||||
return callback(null, doc);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { replSetGetStatus, serverStatus, validateCollection };
|
1494
node_modules/mongodb/lib/operations/collection_ops.js
generated
vendored
Normal file
1494
node_modules/mongodb/lib/operations/collection_ops.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
250
node_modules/mongodb/lib/operations/cursor_ops.js
generated
vendored
Normal file
250
node_modules/mongodb/lib/operations/cursor_ops.js
generated
vendored
Normal file
@@ -0,0 +1,250 @@
|
||||
'use strict';
|
||||
|
||||
const buildCountCommand = require('./collection_ops').buildCountCommand;
|
||||
const formattedOrderClause = require('../utils').formattedOrderClause;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const push = Array.prototype.push;
|
||||
|
||||
let cursor;
|
||||
function loadCursor() {
|
||||
if (!cursor) {
|
||||
cursor = require('../cursor');
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the count of documents for this cursor.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance on which to count.
|
||||
* @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options.
|
||||
* @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options.
|
||||
* @param {Cursor~countResultCallback} [callback] The result callback.
|
||||
*/
|
||||
function count(cursor, applySkipLimit, opts, callback) {
|
||||
if (applySkipLimit) {
|
||||
if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip();
|
||||
if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit();
|
||||
}
|
||||
|
||||
// Ensure we have the right read preference inheritance
|
||||
if (opts.readPreference) {
|
||||
cursor.setReadPreference(opts.readPreference);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof opts.maxTimeMS !== 'number' &&
|
||||
cursor.s.cmd &&
|
||||
typeof cursor.s.cmd.maxTimeMS === 'number'
|
||||
) {
|
||||
opts.maxTimeMS = cursor.s.cmd.maxTimeMS;
|
||||
}
|
||||
|
||||
let options = {};
|
||||
options.skip = opts.skip;
|
||||
options.limit = opts.limit;
|
||||
options.hint = opts.hint;
|
||||
options.maxTimeMS = opts.maxTimeMS;
|
||||
|
||||
// Command
|
||||
const delimiter = cursor.s.ns.indexOf('.');
|
||||
options.collectionName = cursor.s.ns.substr(delimiter + 1);
|
||||
|
||||
let command;
|
||||
try {
|
||||
command = buildCountCommand(cursor, cursor.s.cmd.query, options);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// Set cursor server to the same as the topology
|
||||
cursor.server = cursor.topology.s.coreTopology;
|
||||
|
||||
// Execute the command
|
||||
cursor.s.topology.command(
|
||||
`${cursor.s.ns.substr(0, delimiter)}.$cmd`,
|
||||
command,
|
||||
cursor.s.options,
|
||||
(err, result) => {
|
||||
callback(err, result ? result.result.n : null);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. See Cursor.prototype.each for more information.
|
||||
*
|
||||
* @method
|
||||
* @deprecated
|
||||
* @param {Cursor} cursor The Cursor instance on which to run.
|
||||
* @param {Cursor~resultCallback} callback The result callback.
|
||||
*/
|
||||
function each(cursor, callback) {
|
||||
let Cursor = loadCursor();
|
||||
|
||||
if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true });
|
||||
if (cursor.isNotified()) return;
|
||||
if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) {
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({ message: 'Cursor is closed', driver: true })
|
||||
);
|
||||
}
|
||||
|
||||
if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN;
|
||||
|
||||
// Define function to avoid global scope escape
|
||||
let fn = null;
|
||||
// Trampoline all the entries
|
||||
if (cursor.bufferedCount() > 0) {
|
||||
while ((fn = loop(cursor, callback))) fn(cursor, callback);
|
||||
each(cursor, callback);
|
||||
} else {
|
||||
cursor.next((err, item) => {
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (item == null) {
|
||||
return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null));
|
||||
}
|
||||
|
||||
if (handleCallback(callback, null, item) === false) return;
|
||||
each(cursor, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the cursor.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance on which to run.
|
||||
* @param {Cursor~resultCallback} [callback] The result callback.
|
||||
*/
|
||||
function hasNext(cursor, callback) {
|
||||
let Cursor = loadCursor();
|
||||
|
||||
if (cursor.s.currentDoc) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
if (cursor.isNotified()) {
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
nextObject(cursor, (err, doc) => {
|
||||
if (err) return callback(err, null);
|
||||
if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false);
|
||||
if (!doc) return callback(null, false);
|
||||
cursor.s.currentDoc = doc;
|
||||
callback(null, true);
|
||||
});
|
||||
}
|
||||
|
||||
// Trampoline emptying the number of retrieved items
|
||||
// without incurring a nextTick operation
|
||||
function loop(cursor, callback) {
|
||||
// No more items we are done
|
||||
if (cursor.bufferedCount() === 0) return;
|
||||
// Get the next document
|
||||
cursor._next(callback);
|
||||
// Loop
|
||||
return loop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next available document from the cursor. Returns null if no more documents are available.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance from which to get the next document.
|
||||
* @param {Cursor~resultCallback} [callback] The result callback.
|
||||
*/
|
||||
function next(cursor, callback) {
|
||||
// Return the currentDoc if someone called hasNext first
|
||||
if (cursor.s.currentDoc) {
|
||||
const doc = cursor.s.currentDoc;
|
||||
cursor.s.currentDoc = null;
|
||||
return callback(null, doc);
|
||||
}
|
||||
|
||||
// Return the next object
|
||||
nextObject(cursor, callback);
|
||||
}
|
||||
|
||||
// Get the next available document from the cursor, returns null if no more documents are available.
|
||||
function nextObject(cursor, callback) {
|
||||
let Cursor = loadCursor();
|
||||
|
||||
if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead()))
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({ message: 'Cursor is closed', driver: true })
|
||||
);
|
||||
if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) {
|
||||
try {
|
||||
cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort);
|
||||
} catch (err) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the next object
|
||||
cursor._next((err, doc) => {
|
||||
cursor.s.state = Cursor.OPEN;
|
||||
if (err) return handleCallback(callback, err);
|
||||
handleCallback(callback, null, doc);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of documents. See Cursor.prototype.toArray for more information.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance from which to get the next document.
|
||||
* @param {Cursor~toArrayResultCallback} [callback] The result callback.
|
||||
*/
|
||||
function toArray(cursor, callback) {
|
||||
let Cursor = loadCursor();
|
||||
|
||||
const items = [];
|
||||
|
||||
// Reset cursor
|
||||
cursor.rewind();
|
||||
cursor.s.state = Cursor.INIT;
|
||||
|
||||
// Fetch all the documents
|
||||
const fetchDocs = () => {
|
||||
cursor._next((err, doc) => {
|
||||
if (err) {
|
||||
return cursor._endSession
|
||||
? cursor._endSession(() => handleCallback(callback, err))
|
||||
: handleCallback(callback, err);
|
||||
}
|
||||
if (doc == null) {
|
||||
return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items));
|
||||
}
|
||||
|
||||
// Add doc to items
|
||||
items.push(doc);
|
||||
|
||||
// Get all buffered objects
|
||||
if (cursor.bufferedCount() > 0) {
|
||||
let docs = cursor.readBufferedDocuments(cursor.bufferedCount());
|
||||
|
||||
// Transform the doc if transform method added
|
||||
if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') {
|
||||
docs = docs.map(cursor.s.transforms.doc);
|
||||
}
|
||||
|
||||
push.apply(items, docs);
|
||||
}
|
||||
|
||||
// Attempt a fetch
|
||||
fetchDocs();
|
||||
});
|
||||
};
|
||||
|
||||
fetchDocs();
|
||||
}
|
||||
|
||||
module.exports = { count, each, hasNext, next, toArray };
|
1006
node_modules/mongodb/lib/operations/db_ops.js
generated
vendored
Normal file
1006
node_modules/mongodb/lib/operations/db_ops.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
654
node_modules/mongodb/lib/operations/mongo_client_ops.js
generated
vendored
Normal file
654
node_modules/mongodb/lib/operations/mongo_client_ops.js
generated
vendored
Normal file
@@ -0,0 +1,654 @@
|
||||
'use strict';
|
||||
|
||||
const authenticate = require('../authenticate');
|
||||
const deprecate = require('util').deprecate;
|
||||
const Logger = require('mongodb-core').Logger;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const Mongos = require('../topologies/mongos');
|
||||
const parse = require('mongodb-core').parseConnectionString;
|
||||
const ReadPreference = require('mongodb-core').ReadPreference;
|
||||
const ReplSet = require('../topologies/replset');
|
||||
const Server = require('../topologies/server');
|
||||
const ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool;
|
||||
|
||||
let client;
|
||||
function loadClient() {
|
||||
if (!client) {
|
||||
client = require('../mongo_client');
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
const monitoringEvents = [
|
||||
'timeout',
|
||||
'close',
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed',
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha',
|
||||
'all',
|
||||
'fullsetup',
|
||||
'open'
|
||||
];
|
||||
const ignoreOptionNames = ['native_parser'];
|
||||
const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db'];
|
||||
const legacyParse = deprecate(
|
||||
require('../url_parser'),
|
||||
'current URL string parser is deprecated, and will be removed in a future version. ' +
|
||||
'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.'
|
||||
);
|
||||
const validOptionNames = [
|
||||
'poolSize',
|
||||
'ssl',
|
||||
'sslValidate',
|
||||
'sslCA',
|
||||
'sslCert',
|
||||
'sslKey',
|
||||
'sslPass',
|
||||
'sslCRL',
|
||||
'autoReconnect',
|
||||
'noDelay',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'connectTimeoutMS',
|
||||
'family',
|
||||
'socketTimeoutMS',
|
||||
'reconnectTries',
|
||||
'reconnectInterval',
|
||||
'ha',
|
||||
'haInterval',
|
||||
'replicaSet',
|
||||
'secondaryAcceptableLatencyMS',
|
||||
'acceptableLatencyMS',
|
||||
'connectWithNoPrimary',
|
||||
'authSource',
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'forceServerObjectId',
|
||||
'serializeFunctions',
|
||||
'ignoreUndefined',
|
||||
'raw',
|
||||
'bufferMaxEntries',
|
||||
'readPreference',
|
||||
'pkFactory',
|
||||
'promiseLibrary',
|
||||
'readConcern',
|
||||
'maxStalenessSeconds',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'promoteLongs',
|
||||
'domainsEnabled',
|
||||
'checkServerIdentity',
|
||||
'validateOptions',
|
||||
'appname',
|
||||
'auth',
|
||||
'user',
|
||||
'password',
|
||||
'authMechanism',
|
||||
'compression',
|
||||
'fsync',
|
||||
'readPreferenceTags',
|
||||
'numberOfRetries',
|
||||
'auto_reconnect',
|
||||
'minSize',
|
||||
'monitorCommands',
|
||||
'retryWrites',
|
||||
'useNewUrlParser'
|
||||
];
|
||||
|
||||
function addListeners(mongoClient, topology) {
|
||||
topology.on('authenticated', createListener(mongoClient, 'authenticated'));
|
||||
topology.on('error', createListener(mongoClient, 'error'));
|
||||
topology.on('timeout', createListener(mongoClient, 'timeout'));
|
||||
topology.on('close', createListener(mongoClient, 'close'));
|
||||
topology.on('parseError', createListener(mongoClient, 'parseError'));
|
||||
topology.once('open', createListener(mongoClient, 'open'));
|
||||
topology.once('fullsetup', createListener(mongoClient, 'fullsetup'));
|
||||
topology.once('all', createListener(mongoClient, 'all'));
|
||||
topology.on('reconnect', createListener(mongoClient, 'reconnect'));
|
||||
}
|
||||
|
||||
function assignTopology(client, topology) {
|
||||
client.topology = topology;
|
||||
topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology);
|
||||
}
|
||||
|
||||
// Clear out all events
|
||||
function clearAllEvents(topology) {
|
||||
monitoringEvents.forEach(event => topology.removeAllListeners(event));
|
||||
}
|
||||
|
||||
// Collect all events in order from SDAM
|
||||
function collectEvents(mongoClient, topology) {
|
||||
let MongoClient = loadClient();
|
||||
const collectedEvents = [];
|
||||
|
||||
if (mongoClient instanceof MongoClient) {
|
||||
monitoringEvents.forEach(event => {
|
||||
topology.on(event, (object1, object2) => {
|
||||
if (event === 'open') {
|
||||
collectedEvents.push({ event: event, object1: mongoClient });
|
||||
} else {
|
||||
collectedEvents.push({ event: event, object1: object1, object2: object2 });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return collectedEvents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
|
||||
* @param {string} url The connection URI string
|
||||
* @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options.
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
*/
|
||||
function connect(mongoClient, url, options, callback) {
|
||||
options = Object.assign({}, options);
|
||||
|
||||
// If callback is null throw an exception
|
||||
if (callback == null) {
|
||||
throw new Error('no callback function provided');
|
||||
}
|
||||
|
||||
// Get a logger for MongoClient
|
||||
const logger = Logger('MongoClient', options);
|
||||
|
||||
// Did we pass in a Server/ReplSet/Mongos
|
||||
if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) {
|
||||
return connectWithUrl(mongoClient, url, options, connectCallback);
|
||||
}
|
||||
|
||||
const parseFn = options.useNewUrlParser ? parse : legacyParse;
|
||||
const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions;
|
||||
|
||||
parseFn(url, options, (err, _object) => {
|
||||
// Do not attempt to connect if parsing error
|
||||
if (err) return callback(err);
|
||||
|
||||
// Flatten
|
||||
const object = transform(_object);
|
||||
|
||||
// Parse the string
|
||||
const _finalOptions = createUnifiedOptions(object, options);
|
||||
|
||||
// Check if we have connection and socket timeout set
|
||||
if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000;
|
||||
if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000;
|
||||
|
||||
if (_finalOptions.db_options && _finalOptions.db_options.auth) {
|
||||
delete _finalOptions.db_options.auth;
|
||||
}
|
||||
|
||||
// Store the merged options object
|
||||
mongoClient.s.options = _finalOptions;
|
||||
|
||||
// Failure modes
|
||||
if (object.servers.length === 0) {
|
||||
return callback(new Error('connection string must contain at least one seed host'));
|
||||
}
|
||||
|
||||
// Do we have a replicaset then skip discovery and go straight to connectivity
|
||||
if (_finalOptions.replicaSet || _finalOptions.rs_name) {
|
||||
return createTopology(
|
||||
mongoClient,
|
||||
'replicaset',
|
||||
_finalOptions,
|
||||
connectHandler(mongoClient, _finalOptions, connectCallback)
|
||||
);
|
||||
} else if (object.servers.length > 1) {
|
||||
return createTopology(
|
||||
mongoClient,
|
||||
'mongos',
|
||||
_finalOptions,
|
||||
connectHandler(mongoClient, _finalOptions, connectCallback)
|
||||
);
|
||||
} else {
|
||||
return createServer(
|
||||
mongoClient,
|
||||
_finalOptions,
|
||||
connectHandler(mongoClient, _finalOptions, connectCallback)
|
||||
);
|
||||
}
|
||||
});
|
||||
function connectCallback(err, topology) {
|
||||
const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`;
|
||||
if (err && err.message === 'no mongos proxies found in seed list') {
|
||||
if (logger.isWarn()) {
|
||||
logger.warn(warningMessage);
|
||||
}
|
||||
|
||||
// Return a more specific error message for MongoClient.connect
|
||||
return callback(new MongoError(warningMessage));
|
||||
}
|
||||
|
||||
// Return the error and db instance
|
||||
callback(err, topology);
|
||||
}
|
||||
}
|
||||
|
||||
function connectHandler(client, options, callback) {
|
||||
return (err, topology) => {
|
||||
if (err) {
|
||||
return handleConnectCallback(err, topology, callback);
|
||||
}
|
||||
|
||||
// No authentication just reconnect
|
||||
if (!options.auth) {
|
||||
return handleConnectCallback(err, topology, callback);
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
authenticate(client, options.user, options.password, options, (err, success) => {
|
||||
if (success) {
|
||||
handleConnectCallback(null, topology, callback);
|
||||
} else {
|
||||
if (topology) topology.close();
|
||||
const authError = err ? err : new Error('Could not authenticate user ' + options.auth[0]);
|
||||
handleConnectCallback(authError, topology, callback);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @param {MongoClient} mongoClient The MongoClient instance with which to connect.
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
*/
|
||||
function connectOp(mongoClient, err, callback) {
|
||||
// Did we have a validation error
|
||||
if (err) return callback(err);
|
||||
// Fallback to callback based connect
|
||||
connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => {
|
||||
if (err) return callback(err);
|
||||
callback(null, mongoClient);
|
||||
});
|
||||
}
|
||||
|
||||
function connectWithUrl(mongoClient, url, options, connectCallback) {
|
||||
// Set the topology
|
||||
assignTopology(mongoClient, url);
|
||||
|
||||
// Add listeners
|
||||
addListeners(mongoClient, url);
|
||||
|
||||
// Propagate the events to the client
|
||||
relayEvents(mongoClient, url);
|
||||
|
||||
let finalOptions = Object.assign({}, options);
|
||||
|
||||
// If we have a readPreference passed in by the db options, convert it from a string
|
||||
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
|
||||
finalOptions.readPreference = new ReadPreference(
|
||||
options.readPreference || options.read_preference
|
||||
);
|
||||
}
|
||||
|
||||
// Connect
|
||||
return url.connect(
|
||||
finalOptions,
|
||||
connectHandler(mongoClient, finalOptions, (err, topology) => {
|
||||
if (err) return connectCallback(err, topology);
|
||||
if (finalOptions.user || finalOptions.password || finalOptions.authMechanism) {
|
||||
return authenticate(
|
||||
mongoClient,
|
||||
finalOptions.user,
|
||||
finalOptions.password,
|
||||
finalOptions,
|
||||
err => {
|
||||
if (err) return connectCallback(err, topology);
|
||||
connectCallback(err, topology);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
connectCallback(err, topology);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function createListener(mongoClient, event) {
|
||||
const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']);
|
||||
return (v1, v2) => {
|
||||
if (eventSet.has(event)) {
|
||||
return mongoClient.emit(event, mongoClient);
|
||||
}
|
||||
|
||||
mongoClient.emit(event, v1, v2);
|
||||
};
|
||||
}
|
||||
|
||||
function createServer(mongoClient, options, callback) {
|
||||
// Pass in the promise library
|
||||
options.promiseLibrary = mongoClient.s.promiseLibrary;
|
||||
|
||||
// Set default options
|
||||
const servers = translateOptions(options);
|
||||
|
||||
const server = servers[0];
|
||||
|
||||
// Propagate the events to the client
|
||||
const collectedEvents = collectEvents(mongoClient, server);
|
||||
|
||||
// Connect to topology
|
||||
server.connect(options, (err, topology) => {
|
||||
if (err) {
|
||||
server.close(true);
|
||||
return callback(err);
|
||||
}
|
||||
// Clear out all the collected event listeners
|
||||
clearAllEvents(server);
|
||||
|
||||
// Relay all the events
|
||||
relayEvents(mongoClient, server);
|
||||
// Add listeners
|
||||
addListeners(mongoClient, server);
|
||||
// Check if we are really speaking to a mongos
|
||||
const ismaster = topology.lastIsMaster();
|
||||
|
||||
// Set the topology
|
||||
assignTopology(mongoClient, topology);
|
||||
|
||||
// Do we actually have a mongos
|
||||
if (ismaster && ismaster.msg === 'isdbgrid') {
|
||||
// Destroy the current connection
|
||||
topology.close();
|
||||
// Create mongos connection instead
|
||||
return createTopology(mongoClient, 'mongos', options, callback);
|
||||
}
|
||||
|
||||
// Fire all the events
|
||||
replayEvents(mongoClient, collectedEvents);
|
||||
// Otherwise callback
|
||||
callback(err, topology);
|
||||
});
|
||||
}
|
||||
|
||||
function createTopology(mongoClient, topologyType, options, callback) {
|
||||
// Pass in the promise library
|
||||
options.promiseLibrary = mongoClient.s.promiseLibrary;
|
||||
|
||||
const translationOptions = {};
|
||||
if (topologyType === 'unified') translationOptions.createServers = false;
|
||||
|
||||
// Set default options
|
||||
const servers = translateOptions(options, translationOptions);
|
||||
|
||||
// Create the topology
|
||||
let topology;
|
||||
if (topologyType === 'mongos') {
|
||||
topology = new Mongos(servers, options);
|
||||
} else if (topologyType === 'replicaset') {
|
||||
topology = new ReplSet(servers, options);
|
||||
}
|
||||
|
||||
// Add listeners
|
||||
addListeners(mongoClient, topology);
|
||||
|
||||
// Propagate the events to the client
|
||||
relayEvents(mongoClient, topology);
|
||||
|
||||
// Open the connection
|
||||
topology.connect(options, (err, newTopology) => {
|
||||
if (err) {
|
||||
topology.close(true);
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
assignTopology(mongoClient, newTopology);
|
||||
callback(null, newTopology);
|
||||
});
|
||||
}
|
||||
|
||||
function createUnifiedOptions(finalOptions, options) {
|
||||
const childOptions = [
|
||||
'mongos',
|
||||
'server',
|
||||
'db',
|
||||
'replset',
|
||||
'db_options',
|
||||
'server_options',
|
||||
'rs_options',
|
||||
'mongos_options'
|
||||
];
|
||||
const noMerge = ['readconcern', 'compression'];
|
||||
|
||||
for (const name in options) {
|
||||
if (noMerge.indexOf(name.toLowerCase()) !== -1) {
|
||||
finalOptions[name] = options[name];
|
||||
} else if (childOptions.indexOf(name.toLowerCase()) !== -1) {
|
||||
finalOptions = mergeOptions(finalOptions, options[name], false);
|
||||
} else {
|
||||
if (
|
||||
options[name] &&
|
||||
typeof options[name] === 'object' &&
|
||||
!Buffer.isBuffer(options[name]) &&
|
||||
!Array.isArray(options[name])
|
||||
) {
|
||||
finalOptions = mergeOptions(finalOptions, options[name], true);
|
||||
} else {
|
||||
finalOptions[name] = options[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
function handleConnectCallback(err, topology, callback) {
|
||||
return process.nextTick(() => {
|
||||
try {
|
||||
callback(err, topology);
|
||||
} catch (err) {
|
||||
if (topology) topology.close();
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function legacyTransformUrlOptions(object) {
|
||||
return mergeOptions(createUnifiedOptions({}, object), object, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user from server, fire off on all connections and remove all auth info.
|
||||
*
|
||||
* @method
|
||||
* @param {MongoClient} mongoClient The MongoClient instance on which to logout.
|
||||
* @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function logout(mongoClient, dbName, callback) {
|
||||
mongoClient.topology.logout(dbName, err => {
|
||||
if (err) return callback(err);
|
||||
callback(null, true);
|
||||
});
|
||||
}
|
||||
|
||||
function mergeOptions(target, source, flatten) {
|
||||
for (const name in source) {
|
||||
if (source[name] && typeof source[name] === 'object' && flatten) {
|
||||
target = mergeOptions(target, source[name], flatten);
|
||||
} else {
|
||||
target[name] = source[name];
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function relayEvents(mongoClient, topology) {
|
||||
const serverOrCommandEvents = [
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed',
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha'
|
||||
];
|
||||
|
||||
serverOrCommandEvents.forEach(event => {
|
||||
topology.on(event, (object1, object2) => {
|
||||
mongoClient.emit(event, object1, object2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Replay any events due to single server connection switching to Mongos
|
||||
//
|
||||
function replayEvents(mongoClient, events) {
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
|
||||
}
|
||||
}
|
||||
|
||||
const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => {
|
||||
obj[name.toLowerCase()] = name;
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
function transformUrlOptions(_object) {
|
||||
let object = Object.assign({ servers: _object.hosts }, _object.options);
|
||||
for (let name in object) {
|
||||
const camelCaseName = LEGACY_OPTIONS_MAP[name];
|
||||
if (camelCaseName) {
|
||||
object[camelCaseName] = object[name];
|
||||
}
|
||||
}
|
||||
if (_object.auth) {
|
||||
const auth = _object.auth;
|
||||
for (let i in auth) {
|
||||
if (auth[i]) {
|
||||
object[i] = auth[i];
|
||||
}
|
||||
}
|
||||
|
||||
if (auth.username) {
|
||||
object.auth = auth;
|
||||
object.user = auth.username;
|
||||
}
|
||||
|
||||
if (auth.db) {
|
||||
object.authSource = object.authSource || auth.db;
|
||||
}
|
||||
}
|
||||
|
||||
if (_object.defaultDatabase) {
|
||||
object.dbName = _object.defaultDatabase;
|
||||
}
|
||||
|
||||
if (object.maxpoolsize) {
|
||||
object.poolSize = object.maxpoolsize;
|
||||
}
|
||||
|
||||
if (object.readconcernlevel) {
|
||||
object.readConcern = { level: object.readconcernlevel };
|
||||
}
|
||||
|
||||
if (object.wtimeoutms) {
|
||||
object.wtimeout = object.wtimeoutms;
|
||||
}
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
function translateOptions(options, translationOptions) {
|
||||
translationOptions = Object.assign({}, { createServers: true }, translationOptions);
|
||||
|
||||
// If we have a readPreference passed in by the db options
|
||||
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
|
||||
options.readPreference = new ReadPreference(options.readPreference || options.read_preference);
|
||||
}
|
||||
|
||||
// Do we have readPreference tags, add them
|
||||
if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) {
|
||||
options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags;
|
||||
}
|
||||
|
||||
// Do we have maxStalenessSeconds
|
||||
if (options.maxStalenessSeconds) {
|
||||
options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds;
|
||||
}
|
||||
|
||||
// Set the socket and connection timeouts
|
||||
if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000;
|
||||
if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000;
|
||||
|
||||
if (!translationOptions.createServers) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create server instances
|
||||
return options.servers.map(serverObj => {
|
||||
return serverObj.domain_socket
|
||||
? new Server(serverObj.domain_socket, 27017, options)
|
||||
: new Server(serverObj.host, serverObj.port, options);
|
||||
});
|
||||
}
|
||||
|
||||
// Validate options object
|
||||
function validOptions(options) {
|
||||
const _validOptions = validOptionNames.concat(legacyOptionNames);
|
||||
|
||||
for (const name in options) {
|
||||
if (ignoreOptionNames.indexOf(name) !== -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_validOptions.indexOf(name) === -1 && options.validateOptions) {
|
||||
return new MongoError(`option ${name} is not supported`);
|
||||
} else if (_validOptions.indexOf(name) === -1) {
|
||||
console.warn(`the options [${name}] is not supported`);
|
||||
}
|
||||
|
||||
if (legacyOptionNames.indexOf(name) !== -1) {
|
||||
console.warn(
|
||||
`the server/replset/mongos/db options are deprecated, ` +
|
||||
`all their options are supported at the top level of the options object [${validOptionNames}]`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { connectOp, logout, validOptions };
|
452
node_modules/mongodb/lib/topologies/mongos.js
generated
vendored
Normal file
452
node_modules/mongodb/lib/topologies/mongos.js
generated
vendored
Normal file
@@ -0,0 +1,452 @@
|
||||
'use strict';
|
||||
|
||||
const TopologyBase = require('./topology_base').TopologyBase;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const CMongos = require('mongodb-core').Mongos;
|
||||
const Cursor = require('../cursor');
|
||||
const Server = require('./server');
|
||||
const Store = require('./topology_base').Store;
|
||||
const MAX_JS_INT = require('../utils').MAX_JS_INT;
|
||||
const translateOptions = require('../utils').translateOptions;
|
||||
const filterOptions = require('../utils').filterOptions;
|
||||
const mergeOptions = require('../utils').mergeOptions;
|
||||
|
||||
/**
|
||||
* @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is
|
||||
* used to construct connections.
|
||||
*
|
||||
* **Mongos Should not be used, use MongoClient.connect**
|
||||
*/
|
||||
|
||||
// Allowed parameters
|
||||
var legalOptionNames = [
|
||||
'ha',
|
||||
'haInterval',
|
||||
'acceptableLatencyMS',
|
||||
'poolSize',
|
||||
'ssl',
|
||||
'checkServerIdentity',
|
||||
'sslValidate',
|
||||
'sslCA',
|
||||
'sslCRL',
|
||||
'sslCert',
|
||||
'ciphers',
|
||||
'ecdhCurve',
|
||||
'sslKey',
|
||||
'sslPass',
|
||||
'socketOptions',
|
||||
'bufferMaxEntries',
|
||||
'store',
|
||||
'auto_reconnect',
|
||||
'autoReconnect',
|
||||
'emitError',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectTimeoutMS',
|
||||
'socketTimeoutMS',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'reconnectTries',
|
||||
'appname',
|
||||
'domainsEnabled',
|
||||
'servername',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'promiseLibrary',
|
||||
'monitorCommands'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates a new Mongos instance
|
||||
* @class
|
||||
* @deprecated
|
||||
* @param {Server[]} servers A seedlist of servers participating in the replicaset.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {booelan} [options.ha=true] Turn on high availability monitoring.
|
||||
* @param {number} [options.haInterval=5000] Time between each replicaset status check.
|
||||
* @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
|
||||
* @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection
|
||||
* @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
|
||||
* @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {string} [options.servername] String containing the server name requested via TLS SNI.
|
||||
* @param {object} [options.socketOptions] Socket options
|
||||
* @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
|
||||
* @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting
|
||||
* @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
|
||||
* @fires Mongos#connect
|
||||
* @fires Mongos#ha
|
||||
* @fires Mongos#joined
|
||||
* @fires Mongos#left
|
||||
* @fires Mongos#fullsetup
|
||||
* @fires Mongos#open
|
||||
* @fires Mongos#close
|
||||
* @fires Mongos#error
|
||||
* @fires Mongos#timeout
|
||||
* @fires Mongos#parseError
|
||||
* @fires Mongos#commandStarted
|
||||
* @fires Mongos#commandSucceeded
|
||||
* @fires Mongos#commandFailed
|
||||
* @property {string} parserType the parser type used (c++ or js).
|
||||
* @return {Mongos} a Mongos instance.
|
||||
*/
|
||||
class Mongos extends TopologyBase {
|
||||
constructor(servers, options) {
|
||||
super();
|
||||
|
||||
options = options || {};
|
||||
var self = this;
|
||||
|
||||
// Filter the options
|
||||
options = filterOptions(options, legalOptionNames);
|
||||
|
||||
// Ensure all the instances are Server
|
||||
for (var i = 0; i < servers.length; i++) {
|
||||
if (!(servers[i] instanceof Server)) {
|
||||
throw MongoError.create({
|
||||
message: 'all seed list instances must be of the Server type',
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Stored options
|
||||
var storeOptions = {
|
||||
force: false,
|
||||
bufferMaxEntries:
|
||||
typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT
|
||||
};
|
||||
|
||||
// Shared global store
|
||||
var store = options.store || new Store(self, storeOptions);
|
||||
|
||||
// Build seed list
|
||||
var seedlist = servers.map(function(x) {
|
||||
return { host: x.host, port: x.port };
|
||||
});
|
||||
|
||||
// Get the reconnect option
|
||||
var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true;
|
||||
reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect;
|
||||
|
||||
// Clone options
|
||||
var clonedOptions = mergeOptions(
|
||||
{},
|
||||
{
|
||||
disconnectHandler: store,
|
||||
cursorFactory: Cursor,
|
||||
reconnect: reconnect,
|
||||
emitError: typeof options.emitError === 'boolean' ? options.emitError : true,
|
||||
size: typeof options.poolSize === 'number' ? options.poolSize : 5,
|
||||
monitorCommands:
|
||||
typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false
|
||||
}
|
||||
);
|
||||
|
||||
// Translate any SSL options and other connectivity options
|
||||
clonedOptions = translateOptions(clonedOptions, options);
|
||||
|
||||
// Socket options
|
||||
var socketOptions =
|
||||
options.socketOptions && Object.keys(options.socketOptions).length > 0
|
||||
? options.socketOptions
|
||||
: options;
|
||||
|
||||
// Translate all the options to the mongodb-core ones
|
||||
clonedOptions = translateOptions(clonedOptions, socketOptions);
|
||||
|
||||
// Build default client information
|
||||
clonedOptions.clientInfo = this.clientInfo;
|
||||
// Do we have an application specific string
|
||||
if (options.appname) {
|
||||
clonedOptions.clientInfo.application = { name: options.appname };
|
||||
}
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
// Create the Mongos
|
||||
coreTopology: new CMongos(seedlist, clonedOptions),
|
||||
// Server capabilities
|
||||
sCapabilities: null,
|
||||
// Debug turned on
|
||||
debug: clonedOptions.debug,
|
||||
// Store option defaults
|
||||
storeOptions: storeOptions,
|
||||
// Cloned options
|
||||
clonedOptions: clonedOptions,
|
||||
// Actual store of callbacks
|
||||
store: store,
|
||||
// Options
|
||||
options: options,
|
||||
// Server Session Pool
|
||||
sessionPool: null,
|
||||
// Active client sessions
|
||||
sessions: [],
|
||||
// Promise library
|
||||
promiseLibrary: options.promiseLibrary || Promise
|
||||
};
|
||||
}
|
||||
|
||||
// Connect
|
||||
connect(_options, callback) {
|
||||
var self = this;
|
||||
if ('function' === typeof _options) (callback = _options), (_options = {});
|
||||
if (_options == null) _options = {};
|
||||
if (!('function' === typeof callback)) callback = null;
|
||||
_options = Object.assign({}, this.s.clonedOptions, _options);
|
||||
self.s.options = _options;
|
||||
|
||||
// Update bufferMaxEntries
|
||||
self.s.storeOptions.bufferMaxEntries =
|
||||
typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;
|
||||
|
||||
// Error handler
|
||||
var connectErrorHandler = function() {
|
||||
return function(err) {
|
||||
// Remove all event handlers
|
||||
var events = ['timeout', 'error', 'close'];
|
||||
events.forEach(function(e) {
|
||||
self.removeListener(e, connectErrorHandler);
|
||||
});
|
||||
|
||||
self.s.coreTopology.removeListener('connect', connectErrorHandler);
|
||||
// Force close the topology
|
||||
self.close(true);
|
||||
|
||||
// Try to callback
|
||||
try {
|
||||
callback(err);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Actual handler
|
||||
var errorHandler = function(event) {
|
||||
return function(err) {
|
||||
if (event !== 'error') {
|
||||
self.emit(event, err);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Error handler
|
||||
var reconnectHandler = function() {
|
||||
self.emit('reconnect');
|
||||
self.s.store.execute();
|
||||
};
|
||||
|
||||
// relay the event
|
||||
var relay = function(event) {
|
||||
return function(t, server) {
|
||||
self.emit(event, t, server);
|
||||
};
|
||||
};
|
||||
|
||||
// Connect handler
|
||||
var connectHandler = function() {
|
||||
// Clear out all the current handlers left over
|
||||
var events = ['timeout', 'error', 'close', 'fullsetup'];
|
||||
events.forEach(function(e) {
|
||||
self.s.coreTopology.removeAllListeners(e);
|
||||
});
|
||||
|
||||
// Set up listeners
|
||||
self.s.coreTopology.on('timeout', errorHandler('timeout'));
|
||||
self.s.coreTopology.on('error', errorHandler('error'));
|
||||
self.s.coreTopology.on('close', errorHandler('close'));
|
||||
|
||||
// Set up serverConfig listeners
|
||||
self.s.coreTopology.on('fullsetup', function() {
|
||||
self.emit('fullsetup', self);
|
||||
});
|
||||
|
||||
// Emit open event
|
||||
self.emit('open', null, self);
|
||||
|
||||
// Return correctly
|
||||
try {
|
||||
callback(null, self);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Clear out all the current handlers left over
|
||||
var events = [
|
||||
'timeout',
|
||||
'error',
|
||||
'close',
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed'
|
||||
];
|
||||
events.forEach(function(e) {
|
||||
self.s.coreTopology.removeAllListeners(e);
|
||||
});
|
||||
|
||||
// Set up SDAM listeners
|
||||
self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
|
||||
self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
|
||||
self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
|
||||
self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
|
||||
self.s.coreTopology.on('serverOpening', relay('serverOpening'));
|
||||
self.s.coreTopology.on('serverClosed', relay('serverClosed'));
|
||||
self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));
|
||||
self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));
|
||||
self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
|
||||
self.s.coreTopology.on('commandStarted', relay('commandStarted'));
|
||||
self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));
|
||||
self.s.coreTopology.on('commandFailed', relay('commandFailed'));
|
||||
|
||||
// Set up listeners
|
||||
self.s.coreTopology.once('timeout', connectErrorHandler('timeout'));
|
||||
self.s.coreTopology.once('error', connectErrorHandler('error'));
|
||||
self.s.coreTopology.once('close', connectErrorHandler('close'));
|
||||
self.s.coreTopology.once('connect', connectHandler);
|
||||
// Join and leave events
|
||||
self.s.coreTopology.on('joined', relay('joined'));
|
||||
self.s.coreTopology.on('left', relay('left'));
|
||||
|
||||
// Reconnect server
|
||||
self.s.coreTopology.on('reconnect', reconnectHandler);
|
||||
|
||||
// Start connection
|
||||
self.s.coreTopology.connect(_options);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(Mongos.prototype, 'haInterval', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.s.haInterval;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* A mongos connect event, used to verify that the connection is up and running
|
||||
*
|
||||
* @event Mongos#connect
|
||||
* @type {Mongos}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The mongos high availability event
|
||||
*
|
||||
* @event Mongos#ha
|
||||
* @type {function}
|
||||
* @param {string} type The stage in the high availability event (start|end)
|
||||
* @param {boolean} data.norepeat This is a repeating high availability process or a single execution only
|
||||
* @param {number} data.id The id for this high availability request
|
||||
* @param {object} data.state An object containing the information about the current replicaset
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server member left the mongos set
|
||||
*
|
||||
* @event Mongos#left
|
||||
* @type {function}
|
||||
* @param {string} type The type of member that left (primary|secondary|arbiter)
|
||||
* @param {Server} server The server object that left
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server member joined the mongos set
|
||||
*
|
||||
* @event Mongos#joined
|
||||
* @type {function}
|
||||
* @param {string} type The type of member that joined (primary|secondary|arbiter)
|
||||
* @param {Server} server The server object that joined
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos fullsetup event, emitted when all proxies in the topology have been connected to.
|
||||
*
|
||||
* @event Mongos#fullsetup
|
||||
* @type {Mongos}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos open event, emitted when mongos can start processing commands.
|
||||
*
|
||||
* @event Mongos#open
|
||||
* @type {Mongos}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos close event
|
||||
*
|
||||
* @event Mongos#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos error event, emitted if there is an error listener.
|
||||
*
|
||||
* @event Mongos#error
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos timeout event
|
||||
*
|
||||
* @event Mongos#timeout
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mongos parseError event
|
||||
*
|
||||
* @event Mongos#parseError
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command was started, if command monitoring is enabled
|
||||
*
|
||||
* @event Mongos#commandStarted
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command succeeded, if command monitoring is enabled
|
||||
*
|
||||
* @event Mongos#commandSucceeded
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command failed, if command monitoring is enabled
|
||||
*
|
||||
* @event Mongos#commandFailed
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
module.exports = Mongos;
|
497
node_modules/mongodb/lib/topologies/replset.js
generated
vendored
Normal file
497
node_modules/mongodb/lib/topologies/replset.js
generated
vendored
Normal file
@@ -0,0 +1,497 @@
|
||||
'use strict';
|
||||
|
||||
const Server = require('./server');
|
||||
const Cursor = require('../cursor');
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const TopologyBase = require('./topology_base').TopologyBase;
|
||||
const Store = require('./topology_base').Store;
|
||||
const CReplSet = require('mongodb-core').ReplSet;
|
||||
const MAX_JS_INT = require('../utils').MAX_JS_INT;
|
||||
const translateOptions = require('../utils').translateOptions;
|
||||
const filterOptions = require('../utils').filterOptions;
|
||||
const mergeOptions = require('../utils').mergeOptions;
|
||||
|
||||
/**
|
||||
* @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is
|
||||
* used to construct connections.
|
||||
*
|
||||
* **ReplSet Should not be used, use MongoClient.connect**
|
||||
*/
|
||||
|
||||
// Allowed parameters
|
||||
var legalOptionNames = [
|
||||
'ha',
|
||||
'haInterval',
|
||||
'replicaSet',
|
||||
'rs_name',
|
||||
'secondaryAcceptableLatencyMS',
|
||||
'connectWithNoPrimary',
|
||||
'poolSize',
|
||||
'ssl',
|
||||
'checkServerIdentity',
|
||||
'sslValidate',
|
||||
'sslCA',
|
||||
'sslCert',
|
||||
'ciphers',
|
||||
'ecdhCurve',
|
||||
'sslCRL',
|
||||
'sslKey',
|
||||
'sslPass',
|
||||
'socketOptions',
|
||||
'bufferMaxEntries',
|
||||
'store',
|
||||
'auto_reconnect',
|
||||
'autoReconnect',
|
||||
'emitError',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectTimeoutMS',
|
||||
'socketTimeoutMS',
|
||||
'strategy',
|
||||
'debug',
|
||||
'family',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'reconnectTries',
|
||||
'appname',
|
||||
'domainsEnabled',
|
||||
'servername',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'maxStalenessSeconds',
|
||||
'promiseLibrary',
|
||||
'minSize',
|
||||
'monitorCommands'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates a new ReplSet instance
|
||||
* @class
|
||||
* @deprecated
|
||||
* @param {Server[]} servers A seedlist of servers participating in the replicaset.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.ha=true] Turn on high availability monitoring.
|
||||
* @param {number} [options.haInterval=10000] Time between each replicaset status check.
|
||||
* @param {string} [options.replicaSet] The name of the replicaset to connect to.
|
||||
* @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
|
||||
* @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
|
||||
* @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
|
||||
* @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
|
||||
* @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher.
|
||||
* @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {string} [options.servername] String containing the server name requested via TLS SNI.
|
||||
* @param {object} [options.socketOptions] Socket options
|
||||
* @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
|
||||
* @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting
|
||||
* @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
|
||||
* @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed);
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
|
||||
* @fires ReplSet#connect
|
||||
* @fires ReplSet#ha
|
||||
* @fires ReplSet#joined
|
||||
* @fires ReplSet#left
|
||||
* @fires ReplSet#fullsetup
|
||||
* @fires ReplSet#open
|
||||
* @fires ReplSet#close
|
||||
* @fires ReplSet#error
|
||||
* @fires ReplSet#timeout
|
||||
* @fires ReplSet#parseError
|
||||
* @fires ReplSet#commandStarted
|
||||
* @fires ReplSet#commandSucceeded
|
||||
* @fires ReplSet#commandFailed
|
||||
* @property {string} parserType the parser type used (c++ or js).
|
||||
* @return {ReplSet} a ReplSet instance.
|
||||
*/
|
||||
class ReplSet extends TopologyBase {
|
||||
constructor(servers, options) {
|
||||
super();
|
||||
|
||||
options = options || {};
|
||||
var self = this;
|
||||
|
||||
// Filter the options
|
||||
options = filterOptions(options, legalOptionNames);
|
||||
|
||||
// Ensure all the instances are Server
|
||||
for (var i = 0; i < servers.length; i++) {
|
||||
if (!(servers[i] instanceof Server)) {
|
||||
throw MongoError.create({
|
||||
message: 'all seed list instances must be of the Server type',
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Stored options
|
||||
var storeOptions = {
|
||||
force: false,
|
||||
bufferMaxEntries:
|
||||
typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT
|
||||
};
|
||||
|
||||
// Shared global store
|
||||
var store = options.store || new Store(self, storeOptions);
|
||||
|
||||
// Build seed list
|
||||
var seedlist = servers.map(function(x) {
|
||||
return { host: x.host, port: x.port };
|
||||
});
|
||||
|
||||
// Clone options
|
||||
var clonedOptions = mergeOptions(
|
||||
{},
|
||||
{
|
||||
disconnectHandler: store,
|
||||
cursorFactory: Cursor,
|
||||
reconnect: false,
|
||||
emitError: typeof options.emitError === 'boolean' ? options.emitError : true,
|
||||
size: typeof options.poolSize === 'number' ? options.poolSize : 5,
|
||||
monitorCommands:
|
||||
typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false
|
||||
}
|
||||
);
|
||||
|
||||
// Translate any SSL options and other connectivity options
|
||||
clonedOptions = translateOptions(clonedOptions, options);
|
||||
|
||||
// Socket options
|
||||
var socketOptions =
|
||||
options.socketOptions && Object.keys(options.socketOptions).length > 0
|
||||
? options.socketOptions
|
||||
: options;
|
||||
|
||||
// Translate all the options to the mongodb-core ones
|
||||
clonedOptions = translateOptions(clonedOptions, socketOptions);
|
||||
|
||||
// Build default client information
|
||||
clonedOptions.clientInfo = this.clientInfo;
|
||||
// Do we have an application specific string
|
||||
if (options.appname) {
|
||||
clonedOptions.clientInfo.application = { name: options.appname };
|
||||
}
|
||||
|
||||
// Create the ReplSet
|
||||
var coreTopology = new CReplSet(seedlist, clonedOptions);
|
||||
|
||||
// Listen to reconnect event
|
||||
coreTopology.on('reconnect', function() {
|
||||
self.emit('reconnect');
|
||||
store.execute();
|
||||
});
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
// Replicaset
|
||||
coreTopology: coreTopology,
|
||||
// Server capabilities
|
||||
sCapabilities: null,
|
||||
// Debug tag
|
||||
tag: options.tag,
|
||||
// Store options
|
||||
storeOptions: storeOptions,
|
||||
// Cloned options
|
||||
clonedOptions: clonedOptions,
|
||||
// Store
|
||||
store: store,
|
||||
// Options
|
||||
options: options,
|
||||
// Server Session Pool
|
||||
sessionPool: null,
|
||||
// Active client sessions
|
||||
sessions: [],
|
||||
// Promise library
|
||||
promiseLibrary: options.promiseLibrary || Promise
|
||||
};
|
||||
|
||||
// Debug
|
||||
if (clonedOptions.debug) {
|
||||
// Last ismaster
|
||||
Object.defineProperty(this, 'replset', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return coreTopology;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Connect method
|
||||
connect(_options, callback) {
|
||||
var self = this;
|
||||
if ('function' === typeof _options) (callback = _options), (_options = {});
|
||||
if (_options == null) _options = {};
|
||||
if (!('function' === typeof callback)) callback = null;
|
||||
_options = Object.assign({}, this.s.clonedOptions, _options);
|
||||
self.s.options = _options;
|
||||
|
||||
// Update bufferMaxEntries
|
||||
self.s.storeOptions.bufferMaxEntries =
|
||||
typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;
|
||||
|
||||
// Actual handler
|
||||
var errorHandler = function(event) {
|
||||
return function(err) {
|
||||
if (event !== 'error') {
|
||||
self.emit(event, err);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Clear out all the current handlers left over
|
||||
var events = [
|
||||
'timeout',
|
||||
'error',
|
||||
'close',
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed',
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha'
|
||||
];
|
||||
events.forEach(function(e) {
|
||||
self.s.coreTopology.removeAllListeners(e);
|
||||
});
|
||||
|
||||
// relay the event
|
||||
var relay = function(event) {
|
||||
return function(t, server) {
|
||||
self.emit(event, t, server);
|
||||
};
|
||||
};
|
||||
|
||||
// Replset events relay
|
||||
var replsetRelay = function(event) {
|
||||
return function(t, server) {
|
||||
self.emit(event, t, server.lastIsMaster(), server);
|
||||
};
|
||||
};
|
||||
|
||||
// Relay ha
|
||||
var relayHa = function(t, state) {
|
||||
self.emit('ha', t, state);
|
||||
|
||||
if (t === 'start') {
|
||||
self.emit('ha_connect', t, state);
|
||||
} else if (t === 'end') {
|
||||
self.emit('ha_ismaster', t, state);
|
||||
}
|
||||
};
|
||||
|
||||
// Set up serverConfig listeners
|
||||
self.s.coreTopology.on('joined', replsetRelay('joined'));
|
||||
self.s.coreTopology.on('left', relay('left'));
|
||||
self.s.coreTopology.on('ping', relay('ping'));
|
||||
self.s.coreTopology.on('ha', relayHa);
|
||||
|
||||
// Set up SDAM listeners
|
||||
self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
|
||||
self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
|
||||
self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
|
||||
self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
|
||||
self.s.coreTopology.on('serverOpening', relay('serverOpening'));
|
||||
self.s.coreTopology.on('serverClosed', relay('serverClosed'));
|
||||
self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));
|
||||
self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));
|
||||
self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
|
||||
self.s.coreTopology.on('commandStarted', relay('commandStarted'));
|
||||
self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));
|
||||
self.s.coreTopology.on('commandFailed', relay('commandFailed'));
|
||||
|
||||
self.s.coreTopology.on('fullsetup', function() {
|
||||
self.emit('fullsetup', self, self);
|
||||
});
|
||||
|
||||
self.s.coreTopology.on('all', function() {
|
||||
self.emit('all', null, self);
|
||||
});
|
||||
|
||||
// Connect handler
|
||||
var connectHandler = function() {
|
||||
// Set up listeners
|
||||
self.s.coreTopology.once('timeout', errorHandler('timeout'));
|
||||
self.s.coreTopology.once('error', errorHandler('error'));
|
||||
self.s.coreTopology.once('close', errorHandler('close'));
|
||||
|
||||
// Emit open event
|
||||
self.emit('open', null, self);
|
||||
|
||||
// Return correctly
|
||||
try {
|
||||
callback(null, self);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Error handler
|
||||
var connectErrorHandler = function() {
|
||||
return function(err) {
|
||||
['timeout', 'error', 'close'].forEach(function(e) {
|
||||
self.s.coreTopology.removeListener(e, connectErrorHandler);
|
||||
});
|
||||
|
||||
self.s.coreTopology.removeListener('connect', connectErrorHandler);
|
||||
// Destroy the replset
|
||||
self.s.coreTopology.destroy();
|
||||
|
||||
// Try to callback
|
||||
try {
|
||||
callback(err);
|
||||
} catch (err) {
|
||||
if (!self.s.coreTopology.isConnected())
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Set up listeners
|
||||
self.s.coreTopology.once('timeout', connectErrorHandler('timeout'));
|
||||
self.s.coreTopology.once('error', connectErrorHandler('error'));
|
||||
self.s.coreTopology.once('close', connectErrorHandler('close'));
|
||||
self.s.coreTopology.once('connect', connectHandler);
|
||||
|
||||
// Start connection
|
||||
self.s.coreTopology.connect(_options);
|
||||
}
|
||||
|
||||
close(forceClosed) {
|
||||
super.close(forceClosed);
|
||||
|
||||
['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e));
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(ReplSet.prototype, 'haInterval', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.s.haInterval;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* A replset connect event, used to verify that the connection is up and running
|
||||
*
|
||||
* @event ReplSet#connect
|
||||
* @type {ReplSet}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The replset high availability event
|
||||
*
|
||||
* @event ReplSet#ha
|
||||
* @type {function}
|
||||
* @param {string} type The stage in the high availability event (start|end)
|
||||
* @param {boolean} data.norepeat This is a repeating high availability process or a single execution only
|
||||
* @param {number} data.id The id for this high availability request
|
||||
* @param {object} data.state An object containing the information about the current replicaset
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server member left the replicaset
|
||||
*
|
||||
* @event ReplSet#left
|
||||
* @type {function}
|
||||
* @param {string} type The type of member that left (primary|secondary|arbiter)
|
||||
* @param {Server} server The server object that left
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server member joined the replicaset
|
||||
*
|
||||
* @event ReplSet#joined
|
||||
* @type {function}
|
||||
* @param {string} type The type of member that joined (primary|secondary|arbiter)
|
||||
* @param {Server} server The server object that joined
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet open event, emitted when replicaset can start processing commands.
|
||||
*
|
||||
* @event ReplSet#open
|
||||
* @type {Replset}
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet fullsetup event, emitted when all servers in the topology have been connected to.
|
||||
*
|
||||
* @event ReplSet#fullsetup
|
||||
* @type {Replset}
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet close event
|
||||
*
|
||||
* @event ReplSet#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet error event, emitted if there is an error listener.
|
||||
*
|
||||
* @event ReplSet#error
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet timeout event
|
||||
*
|
||||
* @event ReplSet#timeout
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* ReplSet parseError event
|
||||
*
|
||||
* @event ReplSet#parseError
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command was started, if command monitoring is enabled
|
||||
*
|
||||
* @event ReplSet#commandStarted
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command succeeded, if command monitoring is enabled
|
||||
*
|
||||
* @event ReplSet#commandSucceeded
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command failed, if command monitoring is enabled
|
||||
*
|
||||
* @event ReplSet#commandFailed
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
module.exports = ReplSet;
|
455
node_modules/mongodb/lib/topologies/server.js
generated
vendored
Normal file
455
node_modules/mongodb/lib/topologies/server.js
generated
vendored
Normal file
@@ -0,0 +1,455 @@
|
||||
'use strict';
|
||||
|
||||
const CServer = require('mongodb-core').Server;
|
||||
const Cursor = require('../cursor');
|
||||
const TopologyBase = require('./topology_base').TopologyBase;
|
||||
const Store = require('./topology_base').Store;
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const MAX_JS_INT = require('../utils').MAX_JS_INT;
|
||||
const translateOptions = require('../utils').translateOptions;
|
||||
const filterOptions = require('../utils').filterOptions;
|
||||
const mergeOptions = require('../utils').mergeOptions;
|
||||
|
||||
/**
|
||||
* @fileOverview The **Server** class is a class that represents a single server topology and is
|
||||
* used to construct connections.
|
||||
*
|
||||
* **Server Should not be used, use MongoClient.connect**
|
||||
*/
|
||||
|
||||
// Allowed parameters
|
||||
var legalOptionNames = [
|
||||
'ha',
|
||||
'haInterval',
|
||||
'acceptableLatencyMS',
|
||||
'poolSize',
|
||||
'ssl',
|
||||
'checkServerIdentity',
|
||||
'sslValidate',
|
||||
'sslCA',
|
||||
'sslCRL',
|
||||
'sslCert',
|
||||
'ciphers',
|
||||
'ecdhCurve',
|
||||
'sslKey',
|
||||
'sslPass',
|
||||
'socketOptions',
|
||||
'bufferMaxEntries',
|
||||
'store',
|
||||
'auto_reconnect',
|
||||
'autoReconnect',
|
||||
'emitError',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectTimeoutMS',
|
||||
'socketTimeoutMS',
|
||||
'family',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'reconnectTries',
|
||||
'reconnectInterval',
|
||||
'monitoring',
|
||||
'appname',
|
||||
'domainsEnabled',
|
||||
'servername',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'compression',
|
||||
'promiseLibrary',
|
||||
'monitorCommands'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates a new Server instance
|
||||
* @class
|
||||
* @deprecated
|
||||
* @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host.
|
||||
* @param {number} [port] The server port if IP4.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
|
||||
* @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
|
||||
* @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
|
||||
* @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
|
||||
* @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* @param {string} [options.servername] String containing the server name requested via TLS SNI.
|
||||
* @param {object} [options.socketOptions] Socket options
|
||||
* @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error.
|
||||
* @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
|
||||
* @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting
|
||||
* @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {number} [options.monitoring=true] Triggers the server instance to call ismaster
|
||||
* @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled.
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
|
||||
* @fires Server#connect
|
||||
* @fires Server#close
|
||||
* @fires Server#error
|
||||
* @fires Server#timeout
|
||||
* @fires Server#parseError
|
||||
* @fires Server#reconnect
|
||||
* @fires Server#commandStarted
|
||||
* @fires Server#commandSucceeded
|
||||
* @fires Server#commandFailed
|
||||
* @property {string} parserType the parser type used (c++ or js).
|
||||
* @return {Server} a Server instance.
|
||||
*/
|
||||
class Server extends TopologyBase {
|
||||
constructor(host, port, options) {
|
||||
super();
|
||||
var self = this;
|
||||
|
||||
// Filter the options
|
||||
options = filterOptions(options, legalOptionNames);
|
||||
|
||||
// Promise library
|
||||
const promiseLibrary = options.promiseLibrary;
|
||||
|
||||
// Stored options
|
||||
var storeOptions = {
|
||||
force: false,
|
||||
bufferMaxEntries:
|
||||
typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT
|
||||
};
|
||||
|
||||
// Shared global store
|
||||
var store = options.store || new Store(self, storeOptions);
|
||||
|
||||
// Detect if we have a socket connection
|
||||
if (host.indexOf('/') !== -1) {
|
||||
if (port != null && typeof port === 'object') {
|
||||
options = port;
|
||||
port = null;
|
||||
}
|
||||
} else if (port == null) {
|
||||
throw MongoError.create({ message: 'port must be specified', driver: true });
|
||||
}
|
||||
|
||||
// Get the reconnect option
|
||||
var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true;
|
||||
reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect;
|
||||
|
||||
// Clone options
|
||||
var clonedOptions = mergeOptions(
|
||||
{},
|
||||
{
|
||||
host: host,
|
||||
port: port,
|
||||
disconnectHandler: store,
|
||||
cursorFactory: Cursor,
|
||||
reconnect: reconnect,
|
||||
emitError: typeof options.emitError === 'boolean' ? options.emitError : true,
|
||||
size: typeof options.poolSize === 'number' ? options.poolSize : 5,
|
||||
monitorCommands:
|
||||
typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false
|
||||
}
|
||||
);
|
||||
|
||||
// Translate any SSL options and other connectivity options
|
||||
clonedOptions = translateOptions(clonedOptions, options);
|
||||
|
||||
// Socket options
|
||||
var socketOptions =
|
||||
options.socketOptions && Object.keys(options.socketOptions).length > 0
|
||||
? options.socketOptions
|
||||
: options;
|
||||
|
||||
// Translate all the options to the mongodb-core ones
|
||||
clonedOptions = translateOptions(clonedOptions, socketOptions);
|
||||
|
||||
// Build default client information
|
||||
clonedOptions.clientInfo = this.clientInfo;
|
||||
// Do we have an application specific string
|
||||
if (options.appname) {
|
||||
clonedOptions.clientInfo.application = { name: options.appname };
|
||||
}
|
||||
|
||||
// Define the internal properties
|
||||
this.s = {
|
||||
// Create an instance of a server instance from mongodb-core
|
||||
coreTopology: new CServer(clonedOptions),
|
||||
// Server capabilities
|
||||
sCapabilities: null,
|
||||
// Cloned options
|
||||
clonedOptions: clonedOptions,
|
||||
// Reconnect
|
||||
reconnect: clonedOptions.reconnect,
|
||||
// Emit error
|
||||
emitError: clonedOptions.emitError,
|
||||
// Pool size
|
||||
poolSize: clonedOptions.size,
|
||||
// Store Options
|
||||
storeOptions: storeOptions,
|
||||
// Store
|
||||
store: store,
|
||||
// Host
|
||||
host: host,
|
||||
// Port
|
||||
port: port,
|
||||
// Options
|
||||
options: options,
|
||||
// Server Session Pool
|
||||
sessionPool: null,
|
||||
// Active client sessions
|
||||
sessions: [],
|
||||
// Promise library
|
||||
promiseLibrary: promiseLibrary || Promise
|
||||
};
|
||||
}
|
||||
|
||||
// Connect
|
||||
connect(_options, callback) {
|
||||
var self = this;
|
||||
if ('function' === typeof _options) (callback = _options), (_options = {});
|
||||
if (_options == null) _options = this.s.clonedOptions;
|
||||
if (!('function' === typeof callback)) callback = null;
|
||||
_options = Object.assign({}, this.s.clonedOptions, _options);
|
||||
self.s.options = _options;
|
||||
|
||||
// Update bufferMaxEntries
|
||||
self.s.storeOptions.bufferMaxEntries =
|
||||
typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;
|
||||
|
||||
// Error handler
|
||||
var connectErrorHandler = function() {
|
||||
return function(err) {
|
||||
// Remove all event handlers
|
||||
var events = ['timeout', 'error', 'close'];
|
||||
events.forEach(function(e) {
|
||||
self.s.coreTopology.removeListener(e, connectHandlers[e]);
|
||||
});
|
||||
|
||||
self.s.coreTopology.removeListener('connect', connectErrorHandler);
|
||||
|
||||
// Try to callback
|
||||
try {
|
||||
callback(err);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Actual handler
|
||||
var errorHandler = function(event) {
|
||||
return function(err) {
|
||||
if (event !== 'error') {
|
||||
self.emit(event, err);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Error handler
|
||||
var reconnectHandler = function() {
|
||||
self.emit('reconnect', self);
|
||||
self.s.store.execute();
|
||||
};
|
||||
|
||||
// Reconnect failed
|
||||
var reconnectFailedHandler = function(err) {
|
||||
self.emit('reconnectFailed', err);
|
||||
self.s.store.flush(err);
|
||||
};
|
||||
|
||||
// Destroy called on topology, perform cleanup
|
||||
var destroyHandler = function() {
|
||||
self.s.store.flush();
|
||||
};
|
||||
|
||||
// relay the event
|
||||
var relay = function(event) {
|
||||
return function(t, server) {
|
||||
self.emit(event, t, server);
|
||||
};
|
||||
};
|
||||
|
||||
// Connect handler
|
||||
var connectHandler = function() {
|
||||
// Clear out all the current handlers left over
|
||||
['timeout', 'error', 'close', 'destroy'].forEach(function(e) {
|
||||
self.s.coreTopology.removeAllListeners(e);
|
||||
});
|
||||
|
||||
// Set up listeners
|
||||
self.s.coreTopology.on('timeout', errorHandler('timeout'));
|
||||
self.s.coreTopology.once('error', errorHandler('error'));
|
||||
self.s.coreTopology.on('close', errorHandler('close'));
|
||||
// Only called on destroy
|
||||
self.s.coreTopology.on('destroy', destroyHandler);
|
||||
|
||||
// Emit open event
|
||||
self.emit('open', null, self);
|
||||
|
||||
// Return correctly
|
||||
try {
|
||||
callback(null, self);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Set up listeners
|
||||
var connectHandlers = {
|
||||
timeout: connectErrorHandler('timeout'),
|
||||
error: connectErrorHandler('error'),
|
||||
close: connectErrorHandler('close')
|
||||
};
|
||||
|
||||
// Clear out all the current handlers left over
|
||||
[
|
||||
'timeout',
|
||||
'error',
|
||||
'close',
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed'
|
||||
].forEach(function(e) {
|
||||
self.s.coreTopology.removeAllListeners(e);
|
||||
});
|
||||
|
||||
// Add the event handlers
|
||||
self.s.coreTopology.once('timeout', connectHandlers.timeout);
|
||||
self.s.coreTopology.once('error', connectHandlers.error);
|
||||
self.s.coreTopology.once('close', connectHandlers.close);
|
||||
self.s.coreTopology.once('connect', connectHandler);
|
||||
// Reconnect server
|
||||
self.s.coreTopology.on('reconnect', reconnectHandler);
|
||||
self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler);
|
||||
|
||||
// Set up SDAM listeners
|
||||
self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
|
||||
self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
|
||||
self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
|
||||
self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
|
||||
self.s.coreTopology.on('serverOpening', relay('serverOpening'));
|
||||
self.s.coreTopology.on('serverClosed', relay('serverClosed'));
|
||||
self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));
|
||||
self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));
|
||||
self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
|
||||
self.s.coreTopology.on('commandStarted', relay('commandStarted'));
|
||||
self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));
|
||||
self.s.coreTopology.on('commandFailed', relay('commandFailed'));
|
||||
self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect'));
|
||||
self.s.coreTopology.on('monitoring', relay('monitoring'));
|
||||
|
||||
// Start connection
|
||||
self.s.coreTopology.connect(_options);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(Server.prototype, 'poolSize', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.connections().length;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'autoReconnect', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.reconnect;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'host', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.host;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'port', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.port;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Server connect event
|
||||
*
|
||||
* @event Server#connect
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server close event
|
||||
*
|
||||
* @event Server#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server reconnect event
|
||||
*
|
||||
* @event Server#reconnect
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server error event
|
||||
*
|
||||
* @event Server#error
|
||||
* @type {MongoError}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server timeout event
|
||||
*
|
||||
* @event Server#timeout
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server parseError event
|
||||
*
|
||||
* @event Server#parseError
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command was started, if command monitoring is enabled
|
||||
*
|
||||
* @event Server#commandStarted
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command succeeded, if command monitoring is enabled
|
||||
*
|
||||
* @event Server#commandSucceeded
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted indicating a command failed, if command monitoring is enabled
|
||||
*
|
||||
* @event Server#commandFailed
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
module.exports = Server;
|
446
node_modules/mongodb/lib/topologies/topology_base.js
generated
vendored
Normal file
446
node_modules/mongodb/lib/topologies/topology_base.js
generated
vendored
Normal file
@@ -0,0 +1,446 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events'),
|
||||
MongoError = require('mongodb-core').MongoError,
|
||||
f = require('util').format,
|
||||
os = require('os'),
|
||||
translateReadPreference = require('../utils').translateReadPreference,
|
||||
ClientSession = require('mongodb-core').Sessions.ClientSession;
|
||||
|
||||
// The store of ops
|
||||
var Store = function(topology, storeOptions) {
|
||||
var self = this;
|
||||
var storedOps = [];
|
||||
storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 };
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
storedOps: storedOps,
|
||||
storeOptions: storeOptions,
|
||||
topology: topology
|
||||
};
|
||||
|
||||
Object.defineProperty(this, 'length', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return self.s.storedOps.length;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
Store.prototype.add = function(opType, ns, ops, options, callback) {
|
||||
if (this.s.storeOptions.force) {
|
||||
return callback(MongoError.create({ message: 'db closed by application', driver: true }));
|
||||
}
|
||||
|
||||
if (this.s.storeOptions.bufferMaxEntries === 0) {
|
||||
return callback(
|
||||
MongoError.create({
|
||||
message: f(
|
||||
'no connection available for operation and number of stored operation > %s',
|
||||
this.s.storeOptions.bufferMaxEntries
|
||||
),
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
this.s.storeOptions.bufferMaxEntries > 0 &&
|
||||
this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries
|
||||
) {
|
||||
while (this.s.storedOps.length > 0) {
|
||||
var op = this.s.storedOps.shift();
|
||||
op.c(
|
||||
MongoError.create({
|
||||
message: f(
|
||||
'no connection available for operation and number of stored operation > %s',
|
||||
this.s.storeOptions.bufferMaxEntries
|
||||
),
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback });
|
||||
};
|
||||
|
||||
Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) {
|
||||
if (this.s.storeOptions.force) {
|
||||
return callback(MongoError.create({ message: 'db closed by application', driver: true }));
|
||||
}
|
||||
|
||||
if (this.s.storeOptions.bufferMaxEntries === 0) {
|
||||
return callback(
|
||||
MongoError.create({
|
||||
message: f(
|
||||
'no connection available for operation and number of stored operation > %s',
|
||||
this.s.storeOptions.bufferMaxEntries
|
||||
),
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
this.s.storeOptions.bufferMaxEntries > 0 &&
|
||||
this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries
|
||||
) {
|
||||
while (this.s.storedOps.length > 0) {
|
||||
var op = this.s.storedOps.shift();
|
||||
op.c(
|
||||
MongoError.create({
|
||||
message: f(
|
||||
'no connection available for operation and number of stored operation > %s',
|
||||
this.s.storeOptions.bufferMaxEntries
|
||||
),
|
||||
driver: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback });
|
||||
};
|
||||
|
||||
Store.prototype.flush = function(err) {
|
||||
while (this.s.storedOps.length > 0) {
|
||||
this.s.storedOps
|
||||
.shift()
|
||||
.c(
|
||||
err ||
|
||||
MongoError.create({ message: f('no connection available for operation'), driver: true })
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred'];
|
||||
var secondaryOptions = ['secondary', 'secondaryPreferred'];
|
||||
|
||||
Store.prototype.execute = function(options) {
|
||||
options = options || {};
|
||||
// Get current ops
|
||||
var ops = this.s.storedOps;
|
||||
// Reset the ops
|
||||
this.s.storedOps = [];
|
||||
|
||||
// Unpack options
|
||||
var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true;
|
||||
var executeSecondary =
|
||||
typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true;
|
||||
|
||||
// Execute all the stored ops
|
||||
while (ops.length > 0) {
|
||||
var op = ops.shift();
|
||||
|
||||
if (op.t === 'cursor') {
|
||||
if (executePrimary && executeSecondary) {
|
||||
op.o[op.m].apply(op.o, op.p);
|
||||
} else if (
|
||||
executePrimary &&
|
||||
op.o.options &&
|
||||
op.o.options.readPreference &&
|
||||
primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1
|
||||
) {
|
||||
op.o[op.m].apply(op.o, op.p);
|
||||
} else if (
|
||||
!executePrimary &&
|
||||
executeSecondary &&
|
||||
op.o.options &&
|
||||
op.o.options.readPreference &&
|
||||
secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1
|
||||
) {
|
||||
op.o[op.m].apply(op.o, op.p);
|
||||
}
|
||||
} else if (op.t === 'auth') {
|
||||
this.s.topology[op.t].apply(this.s.topology, op.o);
|
||||
} else {
|
||||
if (executePrimary && executeSecondary) {
|
||||
this.s.topology[op.t](op.n, op.o, op.op, op.c);
|
||||
} else if (
|
||||
executePrimary &&
|
||||
op.op &&
|
||||
op.op.readPreference &&
|
||||
primaryOptions.indexOf(op.op.readPreference.mode) !== -1
|
||||
) {
|
||||
this.s.topology[op.t](op.n, op.o, op.op, op.c);
|
||||
} else if (
|
||||
!executePrimary &&
|
||||
executeSecondary &&
|
||||
op.op &&
|
||||
op.op.readPreference &&
|
||||
secondaryOptions.indexOf(op.op.readPreference.mode) !== -1
|
||||
) {
|
||||
this.s.topology[op.t](op.n, op.o, op.op, op.c);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Store.prototype.all = function() {
|
||||
return this.s.storedOps;
|
||||
};
|
||||
|
||||
// Server capabilities
|
||||
var ServerCapabilities = function(ismaster) {
|
||||
var setup_get_property = function(object, name, value) {
|
||||
Object.defineProperty(object, name, {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Capabilities
|
||||
var aggregationCursor = false;
|
||||
var writeCommands = false;
|
||||
var textSearch = false;
|
||||
var authCommands = false;
|
||||
var listCollections = false;
|
||||
var listIndexes = false;
|
||||
var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000;
|
||||
var commandsTakeWriteConcern = false;
|
||||
var commandsTakeCollation = false;
|
||||
|
||||
if (ismaster.minWireVersion >= 0) {
|
||||
textSearch = true;
|
||||
}
|
||||
|
||||
if (ismaster.maxWireVersion >= 1) {
|
||||
aggregationCursor = true;
|
||||
authCommands = true;
|
||||
}
|
||||
|
||||
if (ismaster.maxWireVersion >= 2) {
|
||||
writeCommands = true;
|
||||
}
|
||||
|
||||
if (ismaster.maxWireVersion >= 3) {
|
||||
listCollections = true;
|
||||
listIndexes = true;
|
||||
}
|
||||
|
||||
if (ismaster.maxWireVersion >= 5) {
|
||||
commandsTakeWriteConcern = true;
|
||||
commandsTakeCollation = true;
|
||||
}
|
||||
|
||||
// If no min or max wire version set to 0
|
||||
if (ismaster.minWireVersion == null) {
|
||||
ismaster.minWireVersion = 0;
|
||||
}
|
||||
|
||||
if (ismaster.maxWireVersion == null) {
|
||||
ismaster.maxWireVersion = 0;
|
||||
}
|
||||
|
||||
// Map up read only parameters
|
||||
setup_get_property(this, 'hasAggregationCursor', aggregationCursor);
|
||||
setup_get_property(this, 'hasWriteCommands', writeCommands);
|
||||
setup_get_property(this, 'hasTextSearch', textSearch);
|
||||
setup_get_property(this, 'hasAuthCommands', authCommands);
|
||||
setup_get_property(this, 'hasListCollectionsCommand', listCollections);
|
||||
setup_get_property(this, 'hasListIndexesCommand', listIndexes);
|
||||
setup_get_property(this, 'minWireVersion', ismaster.minWireVersion);
|
||||
setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion);
|
||||
setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch);
|
||||
setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern);
|
||||
setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation);
|
||||
};
|
||||
|
||||
// Get package.json variable
|
||||
const driverVersion = require('../../package.json').version,
|
||||
nodejsversion = f('Node.js %s, %s', process.version, os.endianness()),
|
||||
type = os.type(),
|
||||
name = process.platform,
|
||||
architecture = process.arch,
|
||||
release = os.release();
|
||||
|
||||
class TopologyBase extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
// Build default client information
|
||||
this.clientInfo = {
|
||||
driver: {
|
||||
name: 'nodejs',
|
||||
version: driverVersion
|
||||
},
|
||||
os: {
|
||||
type: type,
|
||||
name: name,
|
||||
architecture: architecture,
|
||||
version: release
|
||||
},
|
||||
platform: nodejsversion
|
||||
};
|
||||
|
||||
this.setMaxListeners(Infinity);
|
||||
}
|
||||
|
||||
// Sessions related methods
|
||||
hasSessionSupport() {
|
||||
return this.logicalSessionTimeoutMinutes != null;
|
||||
}
|
||||
|
||||
startSession(options, clientOptions) {
|
||||
const session = new ClientSession(this, this.s.sessionPool, options, clientOptions);
|
||||
session.once('ended', () => {
|
||||
this.s.sessions = this.s.sessions.filter(s => !s.equals(session));
|
||||
});
|
||||
|
||||
this.s.sessions.push(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
endSessions(sessions, callback) {
|
||||
return this.s.coreTopology.endSessions(sessions, callback);
|
||||
}
|
||||
|
||||
// Server capabilities
|
||||
capabilities() {
|
||||
if (this.s.sCapabilities) return this.s.sCapabilities;
|
||||
if (this.s.coreTopology.lastIsMaster() == null) return null;
|
||||
this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster());
|
||||
return this.s.sCapabilities;
|
||||
}
|
||||
|
||||
// Command
|
||||
command(ns, cmd, options, callback) {
|
||||
this.s.coreTopology.command(ns, cmd, translateReadPreference(options), callback);
|
||||
}
|
||||
|
||||
// Insert
|
||||
insert(ns, ops, options, callback) {
|
||||
this.s.coreTopology.insert(ns, ops, options, callback);
|
||||
}
|
||||
|
||||
// Update
|
||||
update(ns, ops, options, callback) {
|
||||
this.s.coreTopology.update(ns, ops, options, callback);
|
||||
}
|
||||
|
||||
// Remove
|
||||
remove(ns, ops, options, callback) {
|
||||
this.s.coreTopology.remove(ns, ops, options, callback);
|
||||
}
|
||||
|
||||
// IsConnected
|
||||
isConnected(options) {
|
||||
options = options || {};
|
||||
options = translateReadPreference(options);
|
||||
|
||||
return this.s.coreTopology.isConnected(options);
|
||||
}
|
||||
|
||||
// IsDestroyed
|
||||
isDestroyed() {
|
||||
return this.s.coreTopology.isDestroyed();
|
||||
}
|
||||
|
||||
// Cursor
|
||||
cursor(ns, cmd, options) {
|
||||
options = options || {};
|
||||
options = translateReadPreference(options);
|
||||
options.disconnectHandler = this.s.store;
|
||||
options.topology = this;
|
||||
|
||||
return this.s.coreTopology.cursor(ns, cmd, options);
|
||||
}
|
||||
|
||||
lastIsMaster() {
|
||||
return this.s.coreTopology.lastIsMaster();
|
||||
}
|
||||
|
||||
selectServer(selector, options, callback) {
|
||||
return this.s.coreTopology.selectServer(selector, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unref all sockets
|
||||
* @method
|
||||
*/
|
||||
unref() {
|
||||
return this.s.coreTopology.unref();
|
||||
}
|
||||
|
||||
auth() {
|
||||
var args = Array.prototype.slice.call(arguments, 0);
|
||||
this.s.coreTopology.auth.apply(this.s.coreTopology, args);
|
||||
}
|
||||
|
||||
logout() {
|
||||
var args = Array.prototype.slice.call(arguments, 0);
|
||||
this.s.coreTopology.logout.apply(this.s.coreTopology, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* All raw connections
|
||||
* @method
|
||||
* @return {array}
|
||||
*/
|
||||
connections() {
|
||||
return this.s.coreTopology.connections();
|
||||
}
|
||||
|
||||
close(forceClosed) {
|
||||
// If we have sessions, we want to individually move them to the session pool,
|
||||
// and then send a single endSessions call.
|
||||
if (this.s.sessions.length) {
|
||||
this.s.sessions.forEach(session => session.endSession());
|
||||
}
|
||||
|
||||
if (this.s.sessionPool) {
|
||||
this.s.sessionPool.endAllPooledSessions();
|
||||
}
|
||||
|
||||
this.s.coreTopology.destroy({
|
||||
force: typeof forceClosed === 'boolean' ? forceClosed : false
|
||||
});
|
||||
|
||||
// We need to wash out all stored processes
|
||||
if (forceClosed === true) {
|
||||
this.s.storeOptions.force = forceClosed;
|
||||
this.s.store.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Properties
|
||||
Object.defineProperty(TopologyBase.prototype, 'bson', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.s.bson;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(TopologyBase.prototype, 'parserType', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.parserType;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.logicalSessionTimeoutMinutes;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(TopologyBase.prototype, 'type', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.coreTopology.type;
|
||||
}
|
||||
});
|
||||
|
||||
exports.Store = Store;
|
||||
exports.ServerCapabilities = ServerCapabilities;
|
||||
exports.TopologyBase = TopologyBase;
|
622
node_modules/mongodb/lib/url_parser.js
generated
vendored
Normal file
622
node_modules/mongodb/lib/url_parser.js
generated
vendored
Normal file
@@ -0,0 +1,622 @@
|
||||
'use strict';
|
||||
|
||||
const ReadPreference = require('mongodb-core').ReadPreference,
|
||||
parser = require('url'),
|
||||
f = require('util').format,
|
||||
Logger = require('mongodb-core').Logger,
|
||||
dns = require('dns');
|
||||
|
||||
module.exports = function(url, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = parser.parse(url, true);
|
||||
} catch (e) {
|
||||
return callback(new Error('URL malformed, cannot be parsed'));
|
||||
}
|
||||
|
||||
if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') {
|
||||
return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`'));
|
||||
}
|
||||
|
||||
if (result.protocol === 'mongodb:') {
|
||||
return parseHandler(url, options, callback);
|
||||
}
|
||||
|
||||
// Otherwise parse this as an SRV record
|
||||
if (result.hostname.split('.').length < 3) {
|
||||
return callback(new Error('URI does not have hostname, domain name and tld'));
|
||||
}
|
||||
|
||||
result.domainLength = result.hostname.split('.').length;
|
||||
|
||||
if (result.pathname && result.pathname.match(',')) {
|
||||
return callback(new Error('Invalid URI, cannot contain multiple hostnames'));
|
||||
}
|
||||
|
||||
if (result.port) {
|
||||
return callback(new Error('Ports not accepted with `mongodb+srv` URIs'));
|
||||
}
|
||||
|
||||
let srvAddress = `_mongodb._tcp.${result.host}`;
|
||||
dns.resolveSrv(srvAddress, function(err, addresses) {
|
||||
if (err) return callback(err);
|
||||
|
||||
if (addresses.length === 0) {
|
||||
return callback(new Error('No addresses found at host'));
|
||||
}
|
||||
|
||||
for (let i = 0; i < addresses.length; i++) {
|
||||
if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) {
|
||||
return callback(new Error('Server record does not share hostname with parent URI'));
|
||||
}
|
||||
}
|
||||
|
||||
let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`;
|
||||
let connectionStrings = addresses.map(function(address, i) {
|
||||
if (i === 0) return `${base}${address.name}:${address.port}`;
|
||||
else return `${address.name}:${address.port}`;
|
||||
});
|
||||
|
||||
let connectionString = connectionStrings.join(',') + '/';
|
||||
let connectionStringOptions = [];
|
||||
|
||||
// Add the default database if needed
|
||||
if (result.path) {
|
||||
let defaultDb = result.path.slice(1);
|
||||
if (defaultDb.indexOf('?') !== -1) {
|
||||
defaultDb = defaultDb.slice(0, defaultDb.indexOf('?'));
|
||||
}
|
||||
|
||||
connectionString += defaultDb;
|
||||
}
|
||||
|
||||
// Default to SSL true
|
||||
if (!options.ssl && !result.search) {
|
||||
connectionStringOptions.push('ssl=true');
|
||||
} else if (!options.ssl && result.search && !result.search.match('ssl')) {
|
||||
connectionStringOptions.push('ssl=true');
|
||||
}
|
||||
|
||||
// Keep original uri options
|
||||
if (result.search) {
|
||||
connectionStringOptions.push(result.search.replace('?', ''));
|
||||
}
|
||||
|
||||
dns.resolveTxt(result.host, function(err, record) {
|
||||
if (err && err.code !== 'ENODATA') return callback(err);
|
||||
if (err && err.code === 'ENODATA') record = null;
|
||||
|
||||
if (record) {
|
||||
if (record.length > 1) {
|
||||
return callback(new Error('Multiple text records not allowed'));
|
||||
}
|
||||
|
||||
record = record[0];
|
||||
if (record.length > 1) record = record.join('');
|
||||
else record = record[0];
|
||||
|
||||
if (!record.includes('authSource') && !record.includes('replicaSet')) {
|
||||
return callback(new Error('Text record must only set `authSource` or `replicaSet`'));
|
||||
}
|
||||
|
||||
connectionStringOptions.push(record);
|
||||
}
|
||||
|
||||
// Add any options to the connection string
|
||||
if (connectionStringOptions.length) {
|
||||
connectionString += `?${connectionStringOptions.join('&')}`;
|
||||
}
|
||||
|
||||
parseHandler(connectionString, options, callback);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
function matchesParentDomain(srvAddress, parentDomain) {
|
||||
let regex = /^.*?\./;
|
||||
let srv = `.${srvAddress.replace(regex, '')}`;
|
||||
let parent = `.${parentDomain.replace(regex, '')}`;
|
||||
if (srv.endsWith(parent)) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
function parseHandler(address, options, callback) {
|
||||
let result, err;
|
||||
try {
|
||||
result = parseConnectionString(address, options);
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
|
||||
return err ? callback(err, null) : callback(null, result);
|
||||
}
|
||||
|
||||
function parseConnectionString(url, options) {
|
||||
// Variables
|
||||
let connection_part = '';
|
||||
let auth_part = '';
|
||||
let query_string_part = '';
|
||||
let dbName = 'admin';
|
||||
|
||||
// Url parser result
|
||||
let result = parser.parse(url, true);
|
||||
if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) {
|
||||
throw new Error('No hostname or hostnames provided in connection string');
|
||||
}
|
||||
|
||||
if (result.port === '0') {
|
||||
throw new Error('Invalid port (zero) with hostname');
|
||||
}
|
||||
|
||||
if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) {
|
||||
throw new Error('Invalid port (larger than 65535) with hostname');
|
||||
}
|
||||
|
||||
if (
|
||||
result.path &&
|
||||
result.path.length > 0 &&
|
||||
result.path[0] !== '/' &&
|
||||
url.indexOf('.sock') === -1
|
||||
) {
|
||||
throw new Error('Missing delimiting slash between hosts and options');
|
||||
}
|
||||
|
||||
if (result.query) {
|
||||
for (let name in result.query) {
|
||||
if (name.indexOf('::') !== -1) {
|
||||
throw new Error('Double colon in host identifier');
|
||||
}
|
||||
|
||||
if (result.query[name] === '') {
|
||||
throw new Error('Query parameter ' + name + ' is an incomplete value pair');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result.auth) {
|
||||
let parts = result.auth.split(':');
|
||||
if (url.indexOf(result.auth) !== -1 && parts.length > 2) {
|
||||
throw new Error('Username with password containing an unescaped colon');
|
||||
}
|
||||
|
||||
if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) {
|
||||
throw new Error('Username containing an unescaped at-sign');
|
||||
}
|
||||
}
|
||||
|
||||
// Remove query
|
||||
let clean = url.split('?').shift();
|
||||
|
||||
// Extract the list of hosts
|
||||
let strings = clean.split(',');
|
||||
let hosts = [];
|
||||
|
||||
for (let i = 0; i < strings.length; i++) {
|
||||
let hostString = strings[i];
|
||||
|
||||
if (hostString.indexOf('mongodb') !== -1) {
|
||||
if (hostString.indexOf('@') !== -1) {
|
||||
hosts.push(hostString.split('@').pop());
|
||||
} else {
|
||||
hosts.push(hostString.substr('mongodb://'.length));
|
||||
}
|
||||
} else if (hostString.indexOf('/') !== -1) {
|
||||
hosts.push(hostString.split('/').shift());
|
||||
} else if (hostString.indexOf('/') === -1) {
|
||||
hosts.push(hostString.trim());
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < hosts.length; i++) {
|
||||
let r = parser.parse(f('mongodb://%s', hosts[i].trim()));
|
||||
if (r.path && r.path.indexOf('.sock') !== -1) continue;
|
||||
if (r.path && r.path.indexOf(':') !== -1) {
|
||||
// Not connecting to a socket so check for an extra slash in the hostname.
|
||||
// Using String#split as perf is better than match.
|
||||
if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) {
|
||||
throw new Error('Slash in host identifier');
|
||||
} else {
|
||||
throw new Error('Double colon in host identifier');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a ? mark cut the query elements off
|
||||
if (url.indexOf('?') !== -1) {
|
||||
query_string_part = url.substr(url.indexOf('?') + 1);
|
||||
connection_part = url.substring('mongodb://'.length, url.indexOf('?'));
|
||||
} else {
|
||||
connection_part = url.substring('mongodb://'.length);
|
||||
}
|
||||
|
||||
// Check if we have auth params
|
||||
if (connection_part.indexOf('@') !== -1) {
|
||||
auth_part = connection_part.split('@')[0];
|
||||
connection_part = connection_part.split('@')[1];
|
||||
}
|
||||
|
||||
// Check there is not more than one unescaped slash
|
||||
if (connection_part.split('/').length > 2) {
|
||||
throw new Error(
|
||||
"Unsupported host '" +
|
||||
connection_part.split('?')[0] +
|
||||
"', hosts must be URL encoded and contain at most one unencoded slash"
|
||||
);
|
||||
}
|
||||
|
||||
// Check if the connection string has a db
|
||||
if (connection_part.indexOf('.sock') !== -1) {
|
||||
if (connection_part.indexOf('.sock/') !== -1) {
|
||||
dbName = connection_part.split('.sock/')[1];
|
||||
// Check if multiple database names provided, or just an illegal trailing backslash
|
||||
if (dbName.indexOf('/') !== -1) {
|
||||
if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) {
|
||||
throw new Error('Illegal trailing backslash after database name');
|
||||
}
|
||||
throw new Error('More than 1 database name in URL');
|
||||
}
|
||||
connection_part = connection_part.split(
|
||||
'/',
|
||||
connection_part.indexOf('.sock') + '.sock'.length
|
||||
);
|
||||
}
|
||||
} else if (connection_part.indexOf('/') !== -1) {
|
||||
// Check if multiple database names provided, or just an illegal trailing backslash
|
||||
if (connection_part.split('/').length > 2) {
|
||||
if (connection_part.split('/')[2].length === 0) {
|
||||
throw new Error('Illegal trailing backslash after database name');
|
||||
}
|
||||
throw new Error('More than 1 database name in URL');
|
||||
}
|
||||
dbName = connection_part.split('/')[1];
|
||||
connection_part = connection_part.split('/')[0];
|
||||
}
|
||||
|
||||
// URI decode the host information
|
||||
connection_part = decodeURIComponent(connection_part);
|
||||
|
||||
// Result object
|
||||
let object = {};
|
||||
|
||||
// Pick apart the authentication part of the string
|
||||
let authPart = auth_part || '';
|
||||
let auth = authPart.split(':', 2);
|
||||
|
||||
// Decode the authentication URI components and verify integrity
|
||||
let user = decodeURIComponent(auth[0]);
|
||||
if (auth[0] !== encodeURIComponent(user)) {
|
||||
throw new Error('Username contains an illegal unescaped character');
|
||||
}
|
||||
auth[0] = user;
|
||||
|
||||
if (auth[1]) {
|
||||
let pass = decodeURIComponent(auth[1]);
|
||||
if (auth[1] !== encodeURIComponent(pass)) {
|
||||
throw new Error('Password contains an illegal unescaped character');
|
||||
}
|
||||
auth[1] = pass;
|
||||
}
|
||||
|
||||
// Add auth to final object if we have 2 elements
|
||||
if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] };
|
||||
// if user provided auth options, use that
|
||||
if (options && options.auth != null) object.auth = options.auth;
|
||||
|
||||
// Variables used for temporary storage
|
||||
let hostPart;
|
||||
let urlOptions;
|
||||
let servers;
|
||||
let compression;
|
||||
let serverOptions = { socketOptions: {} };
|
||||
let dbOptions = { read_preference_tags: [] };
|
||||
let replSetServersOptions = { socketOptions: {} };
|
||||
let mongosOptions = { socketOptions: {} };
|
||||
// Add server options to final object
|
||||
object.server_options = serverOptions;
|
||||
object.db_options = dbOptions;
|
||||
object.rs_options = replSetServersOptions;
|
||||
object.mongos_options = mongosOptions;
|
||||
|
||||
// Let's check if we are using a domain socket
|
||||
if (url.match(/\.sock/)) {
|
||||
// Split out the socket part
|
||||
let domainSocket = url.substring(
|
||||
url.indexOf('mongodb://') + 'mongodb://'.length,
|
||||
url.lastIndexOf('.sock') + '.sock'.length
|
||||
);
|
||||
// Clean out any auth stuff if any
|
||||
if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1];
|
||||
domainSocket = decodeURIComponent(domainSocket);
|
||||
servers = [{ domain_socket: domainSocket }];
|
||||
} else {
|
||||
// Split up the db
|
||||
hostPart = connection_part;
|
||||
// Deduplicate servers
|
||||
let deduplicatedServers = {};
|
||||
|
||||
// Parse all server results
|
||||
servers = hostPart
|
||||
.split(',')
|
||||
.map(function(h) {
|
||||
let _host, _port, ipv6match;
|
||||
//check if it matches [IPv6]:port, where the port number is optional
|
||||
if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) {
|
||||
_host = ipv6match[1];
|
||||
_port = parseInt(ipv6match[2], 10) || 27017;
|
||||
} else {
|
||||
//otherwise assume it's IPv4, or plain hostname
|
||||
let hostPort = h.split(':', 2);
|
||||
_host = hostPort[0] || 'localhost';
|
||||
_port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017;
|
||||
// Check for localhost?safe=true style case
|
||||
if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0];
|
||||
}
|
||||
|
||||
// No entry returned for duplicate servr
|
||||
if (deduplicatedServers[_host + '_' + _port]) return null;
|
||||
deduplicatedServers[_host + '_' + _port] = 1;
|
||||
|
||||
// Return the mapped object
|
||||
return { host: _host, port: _port };
|
||||
})
|
||||
.filter(function(x) {
|
||||
return x != null;
|
||||
});
|
||||
}
|
||||
|
||||
// Get the db name
|
||||
object.dbName = dbName || 'admin';
|
||||
// Split up all the options
|
||||
urlOptions = (query_string_part || '').split(/[&;]/);
|
||||
// Ugh, we have to figure out which options go to which constructor manually.
|
||||
urlOptions.forEach(function(opt) {
|
||||
if (!opt) return;
|
||||
var splitOpt = opt.split('='),
|
||||
name = splitOpt[0],
|
||||
value = splitOpt[1];
|
||||
|
||||
// Options implementations
|
||||
switch (name) {
|
||||
case 'slaveOk':
|
||||
case 'slave_ok':
|
||||
serverOptions.slave_ok = value === 'true';
|
||||
dbOptions.slaveOk = value === 'true';
|
||||
break;
|
||||
case 'maxPoolSize':
|
||||
case 'poolSize':
|
||||
serverOptions.poolSize = parseInt(value, 10);
|
||||
replSetServersOptions.poolSize = parseInt(value, 10);
|
||||
break;
|
||||
case 'appname':
|
||||
object.appname = decodeURIComponent(value);
|
||||
break;
|
||||
case 'autoReconnect':
|
||||
case 'auto_reconnect':
|
||||
serverOptions.auto_reconnect = value === 'true';
|
||||
break;
|
||||
case 'ssl':
|
||||
if (value === 'prefer') {
|
||||
serverOptions.ssl = value;
|
||||
replSetServersOptions.ssl = value;
|
||||
mongosOptions.ssl = value;
|
||||
break;
|
||||
}
|
||||
serverOptions.ssl = value === 'true';
|
||||
replSetServersOptions.ssl = value === 'true';
|
||||
mongosOptions.ssl = value === 'true';
|
||||
break;
|
||||
case 'sslValidate':
|
||||
serverOptions.sslValidate = value === 'true';
|
||||
replSetServersOptions.sslValidate = value === 'true';
|
||||
mongosOptions.sslValidate = value === 'true';
|
||||
break;
|
||||
case 'replicaSet':
|
||||
case 'rs_name':
|
||||
replSetServersOptions.rs_name = value;
|
||||
break;
|
||||
case 'reconnectWait':
|
||||
replSetServersOptions.reconnectWait = parseInt(value, 10);
|
||||
break;
|
||||
case 'retries':
|
||||
replSetServersOptions.retries = parseInt(value, 10);
|
||||
break;
|
||||
case 'readSecondary':
|
||||
case 'read_secondary':
|
||||
replSetServersOptions.read_secondary = value === 'true';
|
||||
break;
|
||||
case 'fsync':
|
||||
dbOptions.fsync = value === 'true';
|
||||
break;
|
||||
case 'journal':
|
||||
dbOptions.j = value === 'true';
|
||||
break;
|
||||
case 'safe':
|
||||
dbOptions.safe = value === 'true';
|
||||
break;
|
||||
case 'nativeParser':
|
||||
case 'native_parser':
|
||||
dbOptions.native_parser = value === 'true';
|
||||
break;
|
||||
case 'readConcernLevel':
|
||||
dbOptions.readConcern = { level: value };
|
||||
break;
|
||||
case 'connectTimeoutMS':
|
||||
serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
|
||||
replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
|
||||
mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
|
||||
break;
|
||||
case 'socketTimeoutMS':
|
||||
serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
|
||||
replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
|
||||
mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
|
||||
break;
|
||||
case 'w':
|
||||
dbOptions.w = parseInt(value, 10);
|
||||
if (isNaN(dbOptions.w)) dbOptions.w = value;
|
||||
break;
|
||||
case 'authSource':
|
||||
dbOptions.authSource = value;
|
||||
break;
|
||||
case 'gssapiServiceName':
|
||||
dbOptions.gssapiServiceName = value;
|
||||
break;
|
||||
case 'authMechanism':
|
||||
if (value === 'GSSAPI') {
|
||||
// If no password provided decode only the principal
|
||||
if (object.auth == null) {
|
||||
let urlDecodeAuthPart = decodeURIComponent(authPart);
|
||||
if (urlDecodeAuthPart.indexOf('@') === -1)
|
||||
throw new Error('GSSAPI requires a provided principal');
|
||||
object.auth = { user: urlDecodeAuthPart, password: null };
|
||||
} else {
|
||||
object.auth.user = decodeURIComponent(object.auth.user);
|
||||
}
|
||||
} else if (value === 'MONGODB-X509') {
|
||||
object.auth = { user: decodeURIComponent(authPart) };
|
||||
}
|
||||
|
||||
// Only support GSSAPI or MONGODB-CR for now
|
||||
if (
|
||||
value !== 'GSSAPI' &&
|
||||
value !== 'MONGODB-X509' &&
|
||||
value !== 'MONGODB-CR' &&
|
||||
value !== 'DEFAULT' &&
|
||||
value !== 'SCRAM-SHA-1' &&
|
||||
value !== 'SCRAM-SHA-256' &&
|
||||
value !== 'PLAIN'
|
||||
)
|
||||
throw new Error(
|
||||
'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism'
|
||||
);
|
||||
|
||||
// Authentication mechanism
|
||||
dbOptions.authMechanism = value;
|
||||
break;
|
||||
case 'authMechanismProperties':
|
||||
{
|
||||
// Split up into key, value pairs
|
||||
let values = value.split(',');
|
||||
let o = {};
|
||||
// For each value split into key, value
|
||||
values.forEach(function(x) {
|
||||
let v = x.split(':');
|
||||
o[v[0]] = v[1];
|
||||
});
|
||||
|
||||
// Set all authMechanismProperties
|
||||
dbOptions.authMechanismProperties = o;
|
||||
// Set the service name value
|
||||
if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME;
|
||||
if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM;
|
||||
if (typeof o.CANONICALIZE_HOST_NAME === 'string')
|
||||
dbOptions.gssapiCanonicalizeHostName =
|
||||
o.CANONICALIZE_HOST_NAME === 'true' ? true : false;
|
||||
}
|
||||
break;
|
||||
case 'wtimeoutMS':
|
||||
dbOptions.wtimeout = parseInt(value, 10);
|
||||
break;
|
||||
case 'readPreference':
|
||||
if (!ReadPreference.isValid(value))
|
||||
throw new Error(
|
||||
'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest'
|
||||
);
|
||||
dbOptions.readPreference = value;
|
||||
break;
|
||||
case 'maxStalenessSeconds':
|
||||
dbOptions.maxStalenessSeconds = parseInt(value, 10);
|
||||
break;
|
||||
case 'readPreferenceTags':
|
||||
{
|
||||
// Decode the value
|
||||
value = decodeURIComponent(value);
|
||||
// Contains the tag object
|
||||
let tagObject = {};
|
||||
if (value == null || value === '') {
|
||||
dbOptions.read_preference_tags.push(tagObject);
|
||||
break;
|
||||
}
|
||||
|
||||
// Split up the tags
|
||||
let tags = value.split(/,/);
|
||||
for (let i = 0; i < tags.length; i++) {
|
||||
let parts = tags[i].trim().split(/:/);
|
||||
tagObject[parts[0]] = parts[1];
|
||||
}
|
||||
|
||||
// Set the preferences tags
|
||||
dbOptions.read_preference_tags.push(tagObject);
|
||||
}
|
||||
break;
|
||||
case 'compressors':
|
||||
{
|
||||
compression = serverOptions.compression || {};
|
||||
let compressors = value.split(',');
|
||||
if (
|
||||
!compressors.every(function(compressor) {
|
||||
return compressor === 'snappy' || compressor === 'zlib';
|
||||
})
|
||||
) {
|
||||
throw new Error('Compressors must be at least one of snappy or zlib');
|
||||
}
|
||||
|
||||
compression.compressors = compressors;
|
||||
serverOptions.compression = compression;
|
||||
}
|
||||
break;
|
||||
case 'zlibCompressionLevel':
|
||||
{
|
||||
compression = serverOptions.compression || {};
|
||||
let zlibCompressionLevel = parseInt(value, 10);
|
||||
if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) {
|
||||
throw new Error('zlibCompressionLevel must be an integer between -1 and 9');
|
||||
}
|
||||
|
||||
compression.zlibCompressionLevel = zlibCompressionLevel;
|
||||
serverOptions.compression = compression;
|
||||
}
|
||||
break;
|
||||
case 'retryWrites':
|
||||
dbOptions.retryWrites = value === 'true';
|
||||
break;
|
||||
case 'minSize':
|
||||
dbOptions.minSize = parseInt(value, 10);
|
||||
break;
|
||||
default:
|
||||
{
|
||||
let logger = Logger('URL Parser');
|
||||
logger.warn(`${name} is not supported as a connection string option`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// No tags: should be null (not [])
|
||||
if (dbOptions.read_preference_tags.length === 0) {
|
||||
dbOptions.read_preference_tags = null;
|
||||
}
|
||||
|
||||
// Validate if there are an invalid write concern combinations
|
||||
if (
|
||||
(dbOptions.w === -1 || dbOptions.w === 0) &&
|
||||
(dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true)
|
||||
)
|
||||
throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync');
|
||||
|
||||
// If no read preference set it to primary
|
||||
if (!dbOptions.readPreference) {
|
||||
dbOptions.readPreference = 'primary';
|
||||
}
|
||||
|
||||
// make sure that user-provided options are applied with priority
|
||||
dbOptions = Object.assign(dbOptions, options);
|
||||
|
||||
// Add servers to result
|
||||
object.servers = servers;
|
||||
|
||||
// Returned parsed object
|
||||
return object;
|
||||
}
|
723
node_modules/mongodb/lib/utils.js
generated
vendored
Normal file
723
node_modules/mongodb/lib/utils.js
generated
vendored
Normal file
@@ -0,0 +1,723 @@
|
||||
'use strict';
|
||||
|
||||
const MongoError = require('mongodb-core').MongoError;
|
||||
const ReadPreference = require('mongodb-core').ReadPreference;
|
||||
|
||||
var shallowClone = function(obj) {
|
||||
var copy = {};
|
||||
for (var name in obj) copy[name] = obj[name];
|
||||
return copy;
|
||||
};
|
||||
|
||||
// Figure out the read preference
|
||||
var translateReadPreference = function(options) {
|
||||
var r = null;
|
||||
if (options.readPreference) {
|
||||
r = options.readPreference;
|
||||
} else {
|
||||
return options;
|
||||
}
|
||||
|
||||
if (typeof r === 'string') {
|
||||
options.readPreference = new ReadPreference(r);
|
||||
} else if (r && !(r instanceof ReadPreference) && typeof r === 'object') {
|
||||
const mode = r.mode || r.preference;
|
||||
if (mode && typeof mode === 'string') {
|
||||
options.readPreference = new ReadPreference(mode, r.tags, {
|
||||
maxStalenessSeconds: r.maxStalenessSeconds
|
||||
});
|
||||
}
|
||||
} else if (!(r instanceof ReadPreference)) {
|
||||
throw new TypeError('Invalid read preference: ' + r);
|
||||
}
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
// Set simple property
|
||||
var getSingleProperty = function(obj, name, value) {
|
||||
Object.defineProperty(obj, name, {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var formatSortValue = (exports.formatSortValue = function(sortDirection) {
|
||||
var value = ('' + sortDirection).toLowerCase();
|
||||
|
||||
switch (value) {
|
||||
case 'ascending':
|
||||
case 'asc':
|
||||
case '1':
|
||||
return 1;
|
||||
case 'descending':
|
||||
case 'desc':
|
||||
case '-1':
|
||||
return -1;
|
||||
default:
|
||||
throw new Error(
|
||||
'Illegal sort clause, must be of the form ' +
|
||||
"[['field1', '(ascending|descending)'], " +
|
||||
"['field2', '(ascending|descending)']]"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) {
|
||||
var orderBy = {};
|
||||
if (sortValue == null) return null;
|
||||
if (Array.isArray(sortValue)) {
|
||||
if (sortValue.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (var i = 0; i < sortValue.length; i++) {
|
||||
if (sortValue[i].constructor === String) {
|
||||
orderBy[sortValue[i]] = 1;
|
||||
} else {
|
||||
orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);
|
||||
}
|
||||
}
|
||||
} else if (sortValue != null && typeof sortValue === 'object') {
|
||||
orderBy = sortValue;
|
||||
} else if (typeof sortValue === 'string') {
|
||||
orderBy[sortValue] = 1;
|
||||
} else {
|
||||
throw new Error(
|
||||
'Illegal sort clause, must be of the form ' +
|
||||
"[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"
|
||||
);
|
||||
}
|
||||
|
||||
return orderBy;
|
||||
});
|
||||
|
||||
var checkCollectionName = function checkCollectionName(collectionName) {
|
||||
if ('string' !== typeof collectionName) {
|
||||
throw new MongoError('collection name must be a String');
|
||||
}
|
||||
|
||||
if (!collectionName || collectionName.indexOf('..') !== -1) {
|
||||
throw new MongoError('collection names cannot be empty');
|
||||
}
|
||||
|
||||
if (
|
||||
collectionName.indexOf('$') !== -1 &&
|
||||
collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null
|
||||
) {
|
||||
throw new MongoError("collection names must not contain '$'");
|
||||
}
|
||||
|
||||
if (collectionName.match(/^\.|\.$/) != null) {
|
||||
throw new MongoError("collection names must not start or end with '.'");
|
||||
}
|
||||
|
||||
// Validate that we are not passing 0x00 in the colletion name
|
||||
if (collectionName.indexOf('\x00') !== -1) {
|
||||
throw new MongoError('collection names cannot contain a null character');
|
||||
}
|
||||
};
|
||||
|
||||
var handleCallback = function(callback, err, value1, value2) {
|
||||
try {
|
||||
if (callback == null) return;
|
||||
|
||||
if (callback) {
|
||||
return value2 ? callback(err, value1, value2) : callback(err, value1);
|
||||
}
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wrap a Mongo error document in an Error instance
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var toError = function(error) {
|
||||
if (error instanceof Error) return error;
|
||||
|
||||
var msg = error.err || error.errmsg || error.errMessage || error;
|
||||
var e = MongoError.create({ message: msg, driver: true });
|
||||
|
||||
// Get all object keys
|
||||
var keys = typeof error === 'object' ? Object.keys(error) : [];
|
||||
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
try {
|
||||
e[keys[i]] = error[keys[i]];
|
||||
} catch (err) {
|
||||
// continue
|
||||
}
|
||||
}
|
||||
|
||||
return e;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var normalizeHintField = function normalizeHintField(hint) {
|
||||
var finalHint = null;
|
||||
|
||||
if (typeof hint === 'string') {
|
||||
finalHint = hint;
|
||||
} else if (Array.isArray(hint)) {
|
||||
finalHint = {};
|
||||
|
||||
hint.forEach(function(param) {
|
||||
finalHint[param] = 1;
|
||||
});
|
||||
} else if (hint != null && typeof hint === 'object') {
|
||||
finalHint = {};
|
||||
for (var name in hint) {
|
||||
finalHint[name] = hint[name];
|
||||
}
|
||||
}
|
||||
|
||||
return finalHint;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create index name based on field spec
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var parseIndexOptions = function(fieldOrSpec) {
|
||||
var fieldHash = {};
|
||||
var indexes = [];
|
||||
var keys;
|
||||
|
||||
// Get all the fields accordingly
|
||||
if ('string' === typeof fieldOrSpec) {
|
||||
// 'type'
|
||||
indexes.push(fieldOrSpec + '_' + 1);
|
||||
fieldHash[fieldOrSpec] = 1;
|
||||
} else if (Array.isArray(fieldOrSpec)) {
|
||||
fieldOrSpec.forEach(function(f) {
|
||||
if ('string' === typeof f) {
|
||||
// [{location:'2d'}, 'type']
|
||||
indexes.push(f + '_' + 1);
|
||||
fieldHash[f] = 1;
|
||||
} else if (Array.isArray(f)) {
|
||||
// [['location', '2d'],['type', 1]]
|
||||
indexes.push(f[0] + '_' + (f[1] || 1));
|
||||
fieldHash[f[0]] = f[1] || 1;
|
||||
} else if (isObject(f)) {
|
||||
// [{location:'2d'}, {type:1}]
|
||||
keys = Object.keys(f);
|
||||
keys.forEach(function(k) {
|
||||
indexes.push(k + '_' + f[k]);
|
||||
fieldHash[k] = f[k];
|
||||
});
|
||||
} else {
|
||||
// undefined (ignore)
|
||||
}
|
||||
});
|
||||
} else if (isObject(fieldOrSpec)) {
|
||||
// {location:'2d', type:1}
|
||||
keys = Object.keys(fieldOrSpec);
|
||||
keys.forEach(function(key) {
|
||||
indexes.push(key + '_' + fieldOrSpec[key]);
|
||||
fieldHash[key] = fieldOrSpec[key];
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: indexes.join('_'),
|
||||
keys: keys,
|
||||
fieldHash: fieldHash
|
||||
};
|
||||
};
|
||||
|
||||
var isObject = (exports.isObject = function(arg) {
|
||||
return '[object Object]' === Object.prototype.toString.call(arg);
|
||||
});
|
||||
|
||||
var debugOptions = function(debugFields, options) {
|
||||
var finaloptions = {};
|
||||
debugFields.forEach(function(n) {
|
||||
finaloptions[n] = options[n];
|
||||
});
|
||||
|
||||
return finaloptions;
|
||||
};
|
||||
|
||||
var decorateCommand = function(command, options, exclude) {
|
||||
for (var name in options) {
|
||||
if (exclude.indexOf(name) === -1) command[name] = options[name];
|
||||
}
|
||||
|
||||
return command;
|
||||
};
|
||||
|
||||
var mergeOptions = function(target, source) {
|
||||
for (var name in source) {
|
||||
target[name] = source[name];
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
// Merge options with translation
|
||||
var translateOptions = function(target, source) {
|
||||
var translations = {
|
||||
// SSL translation options
|
||||
sslCA: 'ca',
|
||||
sslCRL: 'crl',
|
||||
sslValidate: 'rejectUnauthorized',
|
||||
sslKey: 'key',
|
||||
sslCert: 'cert',
|
||||
sslPass: 'passphrase',
|
||||
// SocketTimeout translation options
|
||||
socketTimeoutMS: 'socketTimeout',
|
||||
connectTimeoutMS: 'connectionTimeout',
|
||||
// Replicaset options
|
||||
replicaSet: 'setName',
|
||||
rs_name: 'setName',
|
||||
secondaryAcceptableLatencyMS: 'acceptableLatency',
|
||||
connectWithNoPrimary: 'secondaryOnlyConnectionAllowed',
|
||||
// Mongos options
|
||||
acceptableLatencyMS: 'localThresholdMS'
|
||||
};
|
||||
|
||||
for (var name in source) {
|
||||
if (translations[name]) {
|
||||
target[translations[name]] = source[name];
|
||||
} else {
|
||||
target[name] = source[name];
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
var filterOptions = function(options, names) {
|
||||
var filterOptions = {};
|
||||
|
||||
for (var name in options) {
|
||||
if (names.indexOf(name) !== -1) filterOptions[name] = options[name];
|
||||
}
|
||||
|
||||
// Filtered options
|
||||
return filterOptions;
|
||||
};
|
||||
|
||||
// Write concern keys
|
||||
var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync'];
|
||||
|
||||
// Merge the write concern options
|
||||
var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) {
|
||||
// Mix in any allowed options
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) {
|
||||
targetOptions[keys[i]] = sourceOptions[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
// No merging of write concern
|
||||
if (!mergeWriteConcern) return targetOptions;
|
||||
|
||||
// Found no write Concern options
|
||||
var found = false;
|
||||
for (i = 0; i < writeConcernKeys.length; i++) {
|
||||
if (targetOptions[writeConcernKeys[i]]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
for (i = 0; i < writeConcernKeys.length; i++) {
|
||||
if (sourceOptions[writeConcernKeys[i]]) {
|
||||
targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return targetOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Executes the given operation with provided arguments.
|
||||
*
|
||||
* This method reduces large amounts of duplication in the entire codebase by providing
|
||||
* a single point for determining whether callbacks or promises should be used. Additionally
|
||||
* it allows for a single point of entry to provide features such as implicit sessions, which
|
||||
* are required by the Driver Sessions specification in the event that a ClientSession is
|
||||
* not provided
|
||||
*
|
||||
* @param {object} topology The topology to execute this operation on
|
||||
* @param {function} operation The operation to execute
|
||||
* @param {array} args Arguments to apply the provided operation
|
||||
* @param {object} [options] Options that modify the behavior of the method
|
||||
* @param {function]} [options.resultMutator] Allows for the result of the operation to be changed for custom return types
|
||||
*/
|
||||
const executeOperation = (topology, operation, args, options) => {
|
||||
if (topology == null) {
|
||||
throw new TypeError('This method requires a valid topology instance');
|
||||
}
|
||||
|
||||
if (!Array.isArray(args)) {
|
||||
throw new TypeError('This method requires an array of arguments to apply');
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
const Promise = topology.s.promiseLibrary;
|
||||
let resultMutator = options.resultMutator;
|
||||
let callback = args[args.length - 1];
|
||||
|
||||
// The driver sessions spec mandates that we implicitly create sessions for operations
|
||||
// that are not explicitly provided with a session.
|
||||
let session, opOptions, owner;
|
||||
if (!options.skipSessions && topology.hasSessionSupport()) {
|
||||
opOptions = args[args.length - 2];
|
||||
if (opOptions == null || opOptions.session == null) {
|
||||
owner = Symbol();
|
||||
session = topology.startSession({ owner });
|
||||
const optionsIndex = args.length - 2;
|
||||
args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session });
|
||||
} else if (opOptions.session && opOptions.session.hasEnded) {
|
||||
throw new MongoError('Use of expired sessions is not permitted');
|
||||
}
|
||||
}
|
||||
|
||||
const makeExecuteCallback = (resolve, reject) =>
|
||||
function executeCallback(err, result) {
|
||||
if (session && session.owner === owner && !options.returnsCursor) {
|
||||
session.endSession(() => {
|
||||
delete opOptions.session;
|
||||
if (err) return reject(err);
|
||||
if (resultMutator) return resolve(resultMutator(result));
|
||||
resolve(result);
|
||||
});
|
||||
} else {
|
||||
if (err) return reject(err);
|
||||
if (resultMutator) return resolve(resultMutator(result));
|
||||
resolve(result);
|
||||
}
|
||||
};
|
||||
|
||||
// Execute using callback
|
||||
if (typeof callback === 'function') {
|
||||
callback = args.pop();
|
||||
const handler = makeExecuteCallback(
|
||||
result => callback(null, result),
|
||||
err => callback(err, null)
|
||||
);
|
||||
args.push(handler);
|
||||
|
||||
try {
|
||||
return operation.apply(null, args);
|
||||
} catch (e) {
|
||||
handler(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Return a Promise
|
||||
if (args[args.length - 1] != null) {
|
||||
throw new TypeError('final argument to `executeOperation` must be a callback');
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
const handler = makeExecuteCallback(resolve, reject);
|
||||
args[args.length - 1] = handler;
|
||||
|
||||
try {
|
||||
return operation.apply(null, args);
|
||||
} catch (e) {
|
||||
handler(e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies retryWrites: true to a command if retryWrites is set on the command's database.
|
||||
*
|
||||
* @param {object} target The target command to which we will apply retryWrites.
|
||||
* @param {object} db The database from which we can inherit a retryWrites value.
|
||||
*/
|
||||
function applyRetryableWrites(target, db) {
|
||||
if (db && db.s.options.retryWrites) {
|
||||
target.retryWrites = true;
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a write concern to a command based on well defined inheritance rules, optionally
|
||||
* detecting support for the write concern in the first place.
|
||||
*
|
||||
* @param {Object} target the target command we will be applying the write concern to
|
||||
* @param {Object} sources sources where we can inherit default write concerns from
|
||||
* @param {Object} [options] optional settings passed into a command for write concern overrides
|
||||
* @returns {Object} the (now) decorated target
|
||||
*/
|
||||
function applyWriteConcern(target, sources, options) {
|
||||
options = options || {};
|
||||
const db = sources.db;
|
||||
const coll = sources.collection;
|
||||
|
||||
if (options.session && options.session.inTransaction()) {
|
||||
// writeConcern is not allowed within a multi-statement transaction
|
||||
if (target.writeConcern) {
|
||||
delete target.writeConcern;
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
if (options.w != null || options.j != null || options.fsync != null) {
|
||||
const writeConcern = {};
|
||||
if (options.w != null) writeConcern.w = options.w;
|
||||
if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout;
|
||||
if (options.j != null) writeConcern.j = options.j;
|
||||
if (options.fsync != null) writeConcern.fsync = options.fsync;
|
||||
return Object.assign(target, { writeConcern });
|
||||
}
|
||||
|
||||
if (
|
||||
coll &&
|
||||
(coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null)
|
||||
) {
|
||||
return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) });
|
||||
}
|
||||
|
||||
if (
|
||||
db &&
|
||||
(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null)
|
||||
) {
|
||||
return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) });
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a read preference based on well-defined inheritance rules. This method will not only
|
||||
* determine the read preference (if there is one), but will also ensure the returned value is a
|
||||
* properly constructed instance of `ReadPreference`.
|
||||
*
|
||||
* @param {Object} options The options passed into the method, potentially containing a read preference
|
||||
* @param {Object} sources Sources from which we can inherit a read preference
|
||||
* @returns {(ReadPreference|null)} The resolved read preference
|
||||
*/
|
||||
function resolveReadPreference(options, sources) {
|
||||
options = options || {};
|
||||
sources = sources || {};
|
||||
|
||||
const db = sources.db;
|
||||
const coll = sources.collection;
|
||||
const defaultReadPreference = sources.default;
|
||||
const session = options.session;
|
||||
|
||||
let readPreference;
|
||||
if (options.readPreference) {
|
||||
readPreference = options.readPreference;
|
||||
} else if (session && session.inTransaction() && session.transaction.options.readPreference) {
|
||||
// The transaction’s read preference MUST override all other user configurable read preferences.
|
||||
readPreference = session.transaction.options.readPreference;
|
||||
} else {
|
||||
if (coll && coll.s.readPreference) {
|
||||
readPreference = coll.s.readPreference;
|
||||
} else if (db && db.s.readPreference) {
|
||||
readPreference = db.s.readPreference;
|
||||
} else if (defaultReadPreference) {
|
||||
readPreference = defaultReadPreference;
|
||||
}
|
||||
}
|
||||
|
||||
// do we even have a read preference?
|
||||
if (readPreference == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// now attempt to convert the read preference if necessary
|
||||
if (typeof readPreference === 'string') {
|
||||
readPreference = new ReadPreference(readPreference);
|
||||
} else if (
|
||||
readPreference &&
|
||||
!(readPreference instanceof ReadPreference) &&
|
||||
typeof readPreference === 'object'
|
||||
) {
|
||||
const mode = readPreference.mode || readPreference.preference;
|
||||
if (mode && typeof mode === 'string') {
|
||||
readPreference = new ReadPreference(mode, readPreference.tags, {
|
||||
maxStalenessSeconds: readPreference.maxStalenessSeconds
|
||||
});
|
||||
}
|
||||
} else if (!(readPreference instanceof ReadPreference)) {
|
||||
throw new TypeError('Invalid read preference: ' + readPreference);
|
||||
}
|
||||
|
||||
return readPreference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given value is a Promise
|
||||
*
|
||||
* @param {*} maybePromise
|
||||
* @return true if the provided value is a Promise
|
||||
*/
|
||||
function isPromiseLike(maybePromise) {
|
||||
return maybePromise && typeof maybePromise.then === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies collation to a given command.
|
||||
*
|
||||
* @param {object} [command] the command on which to apply collation
|
||||
* @param {(Cursor|Collection)} [target] target of command
|
||||
* @param {object} [options] options containing collation settings
|
||||
*/
|
||||
function decorateWithCollation(command, target, options) {
|
||||
const topology = target.s && target.s.topology;
|
||||
|
||||
if (!topology) {
|
||||
throw new TypeError('parameter "target" is missing a topology');
|
||||
}
|
||||
|
||||
const capabilities = target.s.topology.capabilities();
|
||||
if (options.collation && typeof options.collation === 'object') {
|
||||
if (capabilities && capabilities.commandsTakeCollation) {
|
||||
command.collation = options.collation;
|
||||
} else {
|
||||
throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a read concern to a given command.
|
||||
*
|
||||
* @param {object} command the command on which to apply the read concern
|
||||
* @param {Collection} coll the parent collection of the operation calling this method
|
||||
*/
|
||||
function decorateWithReadConcern(command, coll, options) {
|
||||
if (options && options.session && options.session.inTransaction()) {
|
||||
return;
|
||||
}
|
||||
let readConcern = Object.assign({}, command.readConcern || {});
|
||||
if (coll.s.readConcern) {
|
||||
Object.assign(readConcern, coll.s.readConcern);
|
||||
}
|
||||
|
||||
if (Object.keys(readConcern).length > 0) {
|
||||
Object.assign(command, { readConcern: readConcern });
|
||||
}
|
||||
}
|
||||
|
||||
const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning');
|
||||
const emitConsoleWarning = msg => console.error(msg);
|
||||
const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning;
|
||||
|
||||
/**
|
||||
* Default message handler for generating deprecation warnings.
|
||||
*
|
||||
* @param {string} name function name
|
||||
* @param {string} option option name
|
||||
* @return {string} warning message
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
function defaultMsgHandler(name, option) {
|
||||
return `${name} option [${option}] is deprecated and will be removed in a later version.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deprecates a given function's options.
|
||||
*
|
||||
* @param {object} config configuration for deprecation
|
||||
* @param {string} config.name function name
|
||||
* @param {Array} config.deprecatedOptions options to deprecate
|
||||
* @param {number} config.optionsIndex index of options object in function arguments array
|
||||
* @param {function} [config.msgHandler] optional custom message handler to generate warnings
|
||||
* @param {function} fn the target function of deprecation
|
||||
* @return {function} modified function that warns once per deprecated option, and executes original function
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
function deprecateOptions(config, fn) {
|
||||
if (process.noDeprecation === true) {
|
||||
return fn;
|
||||
}
|
||||
|
||||
const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler;
|
||||
|
||||
const optionsWarned = new Set();
|
||||
function deprecated() {
|
||||
const options = arguments[config.optionsIndex];
|
||||
|
||||
// ensure options is a valid, non-empty object, otherwise short-circuit
|
||||
if (!isObject(options) || Object.keys(options).length === 0) {
|
||||
return fn.apply(this, arguments);
|
||||
}
|
||||
|
||||
config.deprecatedOptions.forEach(deprecatedOption => {
|
||||
if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) {
|
||||
optionsWarned.add(deprecatedOption);
|
||||
const msg = msgHandler(config.name, deprecatedOption);
|
||||
emitDeprecationWarning(msg);
|
||||
if (this && this.getLogger) {
|
||||
const logger = this.getLogger();
|
||||
if (logger) {
|
||||
logger.warn(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return fn.apply(this, arguments);
|
||||
}
|
||||
|
||||
// These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80
|
||||
// The wrapper will keep the same prototype as fn to maintain prototype chain
|
||||
Object.setPrototypeOf(deprecated, fn);
|
||||
if (fn.prototype) {
|
||||
// Setting this (rather than using Object.setPrototype, as above) ensures
|
||||
// that calling the unwrapped constructor gives an instanceof the wrapped
|
||||
// constructor.
|
||||
deprecated.prototype = fn.prototype;
|
||||
}
|
||||
|
||||
return deprecated;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
filterOptions,
|
||||
mergeOptions,
|
||||
translateOptions,
|
||||
shallowClone,
|
||||
getSingleProperty,
|
||||
checkCollectionName,
|
||||
toError,
|
||||
formattedOrderClause,
|
||||
parseIndexOptions,
|
||||
normalizeHintField,
|
||||
handleCallback,
|
||||
decorateCommand,
|
||||
isObject,
|
||||
debugOptions,
|
||||
MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1,
|
||||
mergeOptionsAndWriteConcern,
|
||||
translateReadPreference,
|
||||
executeOperation,
|
||||
applyRetryableWrites,
|
||||
applyWriteConcern,
|
||||
resolveReadPreference,
|
||||
isPromiseLike,
|
||||
decorateWithCollation,
|
||||
decorateWithReadConcern,
|
||||
deprecateOptions
|
||||
};
|
124
node_modules/mongodb/package.json
generated
vendored
Normal file
124
node_modules/mongodb/package.json
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
"mongodb",
|
||||
"/home/beppe/Github/yahooApi"
|
||||
]
|
||||
],
|
||||
"_from": "mongodb@latest",
|
||||
"_hasShrinkwrap": false,
|
||||
"_id": "mongodb@3.1.13",
|
||||
"_inCache": true,
|
||||
"_installable": true,
|
||||
"_location": "/mongodb",
|
||||
"_nodeVersion": "8.15.0",
|
||||
"_npmOperationalInternal": {
|
||||
"host": "s3://npm-registry-packages",
|
||||
"tmp": "tmp/mongodb_3.1.13_1548272001928_0.2889562950753297"
|
||||
},
|
||||
"_npmUser": {
|
||||
"email": "mbroadst@gmail.com",
|
||||
"name": "mbroadst"
|
||||
},
|
||||
"_npmVersion": "6.4.1",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"name": "mongodb",
|
||||
"raw": "mongodb",
|
||||
"rawSpec": "",
|
||||
"scope": null,
|
||||
"spec": "latest",
|
||||
"type": "tag"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz",
|
||||
"_shasum": "f8cdcbb36ad7a08b570bd1271c8525753f75f9f4",
|
||||
"_shrinkwrap": null,
|
||||
"_spec": "mongodb",
|
||||
"_where": "/home/beppe/Github/yahooApi",
|
||||
"bugs": {
|
||||
"url": "https://github.com/mongodb/node-mongodb-native/issues"
|
||||
},
|
||||
"dependencies": {
|
||||
"mongodb-core": "3.1.11",
|
||||
"safe-buffer": "^5.1.2"
|
||||
},
|
||||
"description": "The official MongoDB driver for Node.js",
|
||||
"devDependencies": {
|
||||
"bluebird": "3.5.0",
|
||||
"bson": "^1.0.4",
|
||||
"chai": "^4.1.1",
|
||||
"chai-subset": "^1.6.0",
|
||||
"co": "4.6.0",
|
||||
"coveralls": "^2.11.6",
|
||||
"eslint": "^4.5.0",
|
||||
"eslint-plugin-prettier": "^2.2.0",
|
||||
"istanbul": "^0.4.5",
|
||||
"jsdoc": "3.5.5",
|
||||
"lodash.camelcase": "^4.3.0",
|
||||
"mocha-sinon": "^2.1.0",
|
||||
"mongodb-extjson": "^2.1.1",
|
||||
"mongodb-mock-server": "^1.0.0",
|
||||
"mongodb-test-runner": "^1.1.18",
|
||||
"prettier": "~1.12.0",
|
||||
"semver": "^5.5.0",
|
||||
"sinon": "^4.3.0",
|
||||
"sinon-chai": "^3.2.0",
|
||||
"standard-version": "^4.4.0",
|
||||
"worker-farm": "^1.5.0"
|
||||
},
|
||||
"directories": {},
|
||||
"dist": {
|
||||
"fileCount": 36,
|
||||
"integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==",
|
||||
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcSMGCCRA9TVsSAnZWagAAYTMP/iEA7w+MqlwuPOQ8bKhA\n1bQ1Iw44ecfbRYXS2r963FUbkIgSDL1BEyMWZ6SGr5fK4XFMFCJJRAQIhBNB\nbwuclPEJd+R8pmbCYtHuMyI9kmzXMYEp+Q2uZqL74+0rHB7pVBb+PsB3HCZ0\nqVMoXbp0bRP2Se6/RD6l9s005rwNgQNyHN5f8Xof0nWj6TB6wodU3P/sXAG6\nJTUjfyuF5up6zBRb0ucQrQZusvGW2Pi9rX/T43ATS2HNcjrdpatUex1xwLil\nYPT2aV7r5Q8ouCGUOMfwdSyXUZkGUpr2xHJqLqG8JNzJXF6Ky8LltsEft3pj\n/RtRTi44IIqzQzaUpOJT0XIA8fpFy013zKQn4/SUI5ik7xZT1uEZgzxsS08D\nduyWmbahlzfcTfRF54mI99ekX78AHVyzodHDWnCTtcQBTkJ42sL0IPp/6tJp\nL7x3hUy2acNCAWz9xqZuLLR4mtp1SuQEiyD8QIkwrO5u/+y8dAleBOQKDoVt\neJ2zxnRUDOOmf70XsSwqhpm/22yoWRBPUKFCtrdUZmzYeSzshjJltVu2CdMi\nUzxSfsDLfUDQ2fswJiHDpFlpjEX9btk8m/rL+/YRCZsfLzUZrF3x2Os7DmUq\n44RFONMwZZ3ep8cCB1NwwZs6F2nYc2HNbaw7sDA8+JIwPFWB43TNU1FgNWmi\nn29F\r\n=pvyz\r\n-----END PGP SIGNATURE-----\r\n",
|
||||
"shasum": "f8cdcbb36ad7a08b570bd1271c8525753f75f9f4",
|
||||
"tarball": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz",
|
||||
"unpackedSize": 784227
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
},
|
||||
"gitHead": "c6f417e5fe54691783bccc466e7703a5d380739e",
|
||||
"homepage": "https://github.com/mongodb/node-mongodb-native",
|
||||
"keywords": [
|
||||
"driver",
|
||||
"mongodb",
|
||||
"official"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"main": "index.js",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "christkv",
|
||||
"email": "christkv@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "daprahamian",
|
||||
"email": "dan.aprahamian@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "mbroadst",
|
||||
"email": "mbroadst@gmail.com"
|
||||
}
|
||||
],
|
||||
"name": "mongodb",
|
||||
"optionalDependencies": {},
|
||||
"readme": "ERROR: No README data found!",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "node test/driverBench/",
|
||||
"coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional",
|
||||
"format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'",
|
||||
"generate-evergreen": "node .evergreen/generate_evergreen_tasks.js",
|
||||
"lint": "eslint lib test",
|
||||
"release": "standard-version -i HISTORY.md",
|
||||
"test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional"
|
||||
},
|
||||
"version": "3.1.13"
|
||||
}
|
Reference in New Issue
Block a user