프로젝트

일반

사용자정보

통계
| 개정판:

root / HServer / 00.Server / 00.Program / node_modules / mongodb / README.md

이력 | 보기 | 이력해설 | 다운로드 (14.5 KB)

1 39 HKM
[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/)
2
3
[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native)
4
[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1)
5
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
6
7
# Description
8
9
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.
10
11
**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).**
12
13
## MongoDB Node.JS Driver
14
15
| what          | where                                          |
16
|---------------|------------------------------------------------|
17
| documentation | http://mongodb.github.io/node-mongodb-native  |
18
| api-doc        | http://mongodb.github.io/node-mongodb-native/3.0/api  |
19
| source        | https://github.com/mongodb/node-mongodb-native |
20
| mongodb       | http://www.mongodb.org                        |
21
22
### Bugs / Feature Requests
23
24
Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
25
case in our issue management tool, JIRA:
26
27
- Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
28
- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
29
- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
30
31
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
32
Core Server (i.e. SERVER) project are **public**.
33
34
### Questions and Bug Reports
35
36
 * Mailing List: [groups.google.com/forum/#!forum/node-mongodb-native](https://groups.google.com/forum/#!forum/node-mongodb-native)
37
 * JIRA: [jira.mongodb.org](http://jira.mongodb.org)
38
39
### Change Log
40
41
Change history can be found in [`HISTORY.md`](HISTORY.md).
42
43
# Installation
44
45
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.
46
47
## MongoDB Driver
48
49
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.
50
51
```bash
52
npm install mongodb --save
53
```
54
55
This will download the MongoDB driver and add a dependency entry in your `package.json` file.
56
57
You can also use the [Yarn](https://yarnpkg.com/en) package manager.
58
59
## Troubleshooting
60
61
The MongoDB driver depends on several other packages. These are:
62
63
* [mongodb-core](https://github.com/mongodb-js/mongodb-core)
64
* [bson](https://github.com/mongodb/js-bson)
65
* [kerberos](https://github.com/mongodb-js/kerberos)
66
* [node-gyp](https://github.com/nodejs/node-gyp)
67
68
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.
69
70
**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.**
71
72
### Diagnosing on UNIX
73
74
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.
75
76
```bash
77
git clone https://github.com/mongodb-js/kerberos
78
cd kerberos
79
npm install
80
```
81
82
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:
83
84
```bash
85
npm install -g node-gyp
86
```
87
88
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.
89
90
```bash
91
cd yourproject
92
npm install mongodb --save
93
```
94
95
If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
96
97
```bash
98
npm --loglevel verbose install mongodb
99
```
100
101
This will print out all the steps npm is performing while trying to install the module.
102
103
### Diagnosing on Windows
104
105
A compiler tool chain known to work for compiling `kerberos` on Windows is the following.
106
107
* Visual Studio C++ 2010 (do not use higher versions)
108
* Windows 7 64bit SDK
109
* Python 2.7 or higher
110
111
Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`.
112
113
```bash
114
npm install -g node-gyp
115
```
116
117
Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
118
119
```bash
120
git clone https://github.com/christkv/kerberos.git
121
cd kerberos
122
npm install
123
node-gyp rebuild
124
```
125
126
This should rebuild the driver successfully if you have everything set up correctly.
127
128
### Other possible issues
129
130
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).
131
132
Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
133
134
## Quick Start
135
136
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).
137
138
### Create the `package.json` file
139
140
First, create a directory where your application will live.
141
142
```bash
143
mkdir myproject
144
cd myproject
145
```
146
147
Enter the following command and answer the questions to create the initial structure for your new project:
148
149
```bash
150
npm init
151
```
152
153
Next, install the driver dependency.
154
155
```bash
156
npm install mongodb --save
157
```
158
159
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.
160
161
### Start a MongoDB Server
162
163
For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
164
165
1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
166
2. Create a database directory (in this case under **/data**).
167
3. Install and start a ``mongod`` process.
168
169
```bash
170
mongod --dbpath=/data
171
```
172
173
You should see the **mongod** process start up and print some status information.
174
175
### Connect to MongoDB
176
177
Create a new **app.js** file and add the following code to try out some basic CRUD
178
operations using the MongoDB driver.
179
180
Add code to connect to the server and the database **myproject**:
181
182
```js
183
const MongoClient = require('mongodb').MongoClient;
184
const assert = require('assert');
185
186
// Connection URL
187
const url = 'mongodb://localhost:27017';
188
189
// Database Name
190
const dbName = 'myproject';
191
192
// Use connect method to connect to the server
193
MongoClient.connect(url, function(err, client) {
194
  assert.equal(null, err);
195
  console.log("Connected successfully to server");
196
197
  const db = client.db(dbName);
198
199
  client.close();
200
});
201
```
202
203
Run your app from the command line with:
204
205
```bash
206
node app.js
207
```
208
209
The application should print **Connected successfully to server** to the console.
210
211
### Insert a Document
212
213
Add to **app.js** the following function which uses the **insertMany**
214
method to add three documents to the **documents** collection.
215
216
```js
217
const insertDocuments = function(db, callback) {
218
  // Get the documents collection
219
  const collection = db.collection('documents');
220
  // Insert some documents
221
  collection.insertMany([
222
    {a : 1}, {a : 2}, {a : 3}
223
  ], function(err, result) {
224
    assert.equal(err, null);
225
    assert.equal(3, result.result.n);
226
    assert.equal(3, result.ops.length);
227
    console.log("Inserted 3 documents into the collection");
228
    callback(result);
229
  });
230
}
231
```
232
233
The **insert** command returns an object with the following fields:
234
235
* **result** Contains the result document from MongoDB
236
* **ops** Contains the documents inserted with added **_id** fields
237
* **connection** Contains the connection used to perform the insert
238
239
Add the following code to call the **insertDocuments** function:
240
241
```js
242
const MongoClient = require('mongodb').MongoClient;
243
const assert = require('assert');
244
245
// Connection URL
246
const url = 'mongodb://localhost:27017';
247
248
// Database Name
249
const dbName = 'myproject';
250
251
// Use connect method to connect to the server
252
MongoClient.connect(url, function(err, client) {
253
  assert.equal(null, err);
254
  console.log("Connected successfully to server");
255
256
  const db = client.db(dbName);
257
258
  insertDocuments(db, function() {
259
    client.close();
260
  });
261
});
262
```
263
264
Run the updated **app.js** file:
265
266
```bash
267
node app.js
268
```
269
270
The operation returns the following output:
271
272
```bash
273
Connected successfully to server
274
Inserted 3 documents into the collection
275
```
276
277
### Find All Documents
278
279
Add a query that returns all the documents.
280
281
```js
282
const findDocuments = function(db, callback) {
283
  // Get the documents collection
284
  const collection = db.collection('documents');
285
  // Find some documents
286
  collection.find({}).toArray(function(err, docs) {
287
    assert.equal(err, null);
288
    console.log("Found the following records");
289
    console.log(docs)
290
    callback(docs);
291
  });
292
}
293
```
294
295
This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback:
296
297
```js
298
const MongoClient = require('mongodb').MongoClient;
299
const assert = require('assert');
300
301
// Connection URL
302
const url = 'mongodb://localhost:27017';
303
304
// Database Name
305
const dbName = 'myproject';
306
307
// Use connect method to connect to the server
308
MongoClient.connect(url, function(err, client) {
309
  assert.equal(null, err);
310
  console.log("Connected correctly to server");
311
312
  const db = client.db(dbName);
313
314
  insertDocuments(db, function() {
315
    findDocuments(db, function() {
316
      client.close();
317
    });
318
  });
319
});
320
```
321
322
### Find Documents with a Query Filter
323
324
Add a query filter to find only documents which meet the query criteria.
325
326
```js
327
const findDocuments = function(db, callback) {
328
  // Get the documents collection
329
  const collection = db.collection('documents');
330
  // Find some documents
331
  collection.find({'a': 3}).toArray(function(err, docs) {
332
    assert.equal(err, null);
333
    console.log("Found the following records");
334
    console.log(docs);
335
    callback(docs);
336
  });
337
}
338
```
339
340
Only the documents which match ``'a' : 3`` should be returned.
341
342
### Update a document
343
344
The following operation updates a document in the **documents** collection.
345
346
```js
347
const updateDocument = function(db, callback) {
348
  // Get the documents collection
349
  const collection = db.collection('documents');
350
  // Update document where a is 2, set b equal to 1
351
  collection.updateOne({ a : 2 }
352
    , { $set: { b : 1 } }, function(err, result) {
353
    assert.equal(err, null);
354
    assert.equal(1, result.result.n);
355
    console.log("Updated the document with the field a equal to 2");
356
    callback(result);
357
  });
358
}
359
```
360
361
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.
362
363
```js
364
const MongoClient = require('mongodb').MongoClient;
365
const assert = require('assert');
366
367
// Connection URL
368
const url = 'mongodb://localhost:27017';
369
370
// Database Name
371
const dbName = 'myproject';
372
373
// Use connect method to connect to the server
374
MongoClient.connect(url, function(err, client) {
375
  assert.equal(null, err);
376
  console.log("Connected successfully to server");
377
378
  const db = client.db(dbName);
379
380
  insertDocuments(db, function() {
381
    updateDocument(db, function() {
382
      client.close();
383
    });
384
  });
385
});
386
```
387
388
### Remove a document
389
390
Remove the document where the field **a** is equal to **3**.
391
392
```js
393
const removeDocument = function(db, callback) {
394
  // Get the documents collection
395
  const collection = db.collection('documents');
396
  // Delete document where a is 3
397
  collection.deleteOne({ a : 3 }, function(err, result) {
398
    assert.equal(err, null);
399
    assert.equal(1, result.result.n);
400
    console.log("Removed the document with the field a equal to 3");
401
    callback(result);
402
  });
403
}
404
```
405
406
Add the new method to the **MongoClient.connect** callback function.
407
408
```js
409
const MongoClient = require('mongodb').MongoClient;
410
const assert = require('assert');
411
412
// Connection URL
413
const url = 'mongodb://localhost:27017';
414
415
// Database Name
416
const dbName = 'myproject';
417
418
// Use connect method to connect to the server
419
MongoClient.connect(url, function(err, client) {
420
  assert.equal(null, err);
421
  console.log("Connected successfully to server");
422
423
  const db = client.db(dbName);
424
425
  insertDocuments(db, function() {
426
    updateDocument(db, function() {
427
      removeDocument(db, function() {
428
        client.close();
429
      });
430
    });
431
  });
432
});
433
```
434
435
### Index a Collection
436
437
[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
438
performance. The following function creates an index on the **a** field in the
439
**documents** collection.
440
441
```js
442
const indexCollection = function(db, callback) {
443
  db.collection('documents').createIndex(
444
    { "a": 1 },
445
      null,
446
      function(err, results) {
447
        console.log(results);
448
        callback();
449
    }
450
  );
451
};
452
```
453
454
Add the ``indexCollection`` method to your app:
455
456
```js
457
const MongoClient = require('mongodb').MongoClient;
458
const assert = require('assert');
459
460
// Connection URL
461
const url = 'mongodb://localhost:27017';
462
463
const dbName = 'myproject';
464
465
// Use connect method to connect to the server
466
MongoClient.connect(url, function(err, client) {
467
  assert.equal(null, err);
468
  console.log("Connected successfully to server");
469
470
  const db = client.db(dbName);
471
472
  insertDocuments(db, function() {
473
    indexCollection(db, function() {
474
      client.close();
475
    });
476
  });
477
});
478
```
479
480
For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md).
481
482
## Next Steps
483
484
 * [MongoDB Documentation](http://mongodb.org)
485
 * [Read about Schemas](http://learnmongodbthehardway.com)
486
 * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)