PageRenderTime 36ms CodeModel.GetById 14ms app.highlight 18ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/mongodb/README.md

https://bitbucket.org/coleman333/smartsite
Markdown | 415 lines | 315 code | 100 blank | 0 comment | 0 complexity | d98ce121c4ee28264ff01e4714292514 MD5 | raw file
  1[![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
  9The 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## MongoDB Node.JS Driver
 12
 13| what          | where                                          |
 14|---------------|------------------------------------------------|
 15| documentation | http://mongodb.github.io/node-mongodb-native/  |
 16| api-doc        | http://mongodb.github.io/node-mongodb-native/2.2/api/  |
 17| source        | https://github.com/mongodb/node-mongodb-native |
 18| mongodb       | http://www.mongodb.org/                        |
 19
 20### Blogs of Engineers involved in the driver
 21- Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com>
 22
 23### Bugs / Feature Requests
 24
 25Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a
 26case in our issue management tool, JIRA:
 27
 28- Create an account and login <https://jira.mongodb.org>.
 29- Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>.
 30- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
 31
 32Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
 33Core Server (i.e. SERVER) project are **public**.
 34
 35### Questions and Bug Reports
 36
 37 * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native
 38 * jira: http://jira.mongodb.org/
 39
 40### Change Log
 41
 42http://jira.mongodb.org/browse/NODE
 43
 44# Installation
 45
 46The recommended way to get started using the Node.js 2.0 driver is by using the `NPM` (Node Package Manager) to install the dependency in your project.
 47
 48## MongoDB Driver
 49
 50Given that you have created your own project using `npm init` we install the mongodb driver and it's dependencies by executing the following `NPM` command.
 51
 52```
 53npm install mongodb --save
 54```
 55
 56This will download the MongoDB driver and add a dependency entry in your `package.json` file.
 57
 58## Troubleshooting
 59
 60The MongoDB driver depends on several other packages. These are.
 61
 62* mongodb-core
 63* bson
 64* kerberos
 65* node-gyp
 66
 67The `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 to be able 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 what libraries to install.
 68
 69{{% note class="important" %}}
 70Windows 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{{% /note %}}
 72
 73### Diagnosing on UNIX
 74
 75If you don’t have the build essentials it won’t build. In the case of linux you will need gcc and 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.
 76
 77```
 78git clone https://github.com/christkv/kerberos.git
 79cd kerberos
 80npm install
 81```
 82
 83If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing.
 84
 85```
 86npm install -g node-gyp
 87```
 88
 89If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command.
 90
 91```
 92cd yourproject
 93npm install mongodb --save
 94```
 95
 96If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
 97
 98```
 99npm --loglevel verbose install mongodb
100```
101
102This will print out all the steps npm is performing while trying to install the module.
103
104### Diagnosing on Windows
105
106A known compiler tool chain known to work for compiling `kerberos` on windows is the following.
107
108* Visual Studio c++ 2010 (do not use higher versions)
109* Windows 7 64bit SDK
110* Python 2.7 or higher
111
112Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp.
113
114```
115npm install -g node-gyp
116```
117
118Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo.
119
120```
121git clone https://github.com/christkv/kerberos.git
122cd kerberos
123npm install
124node-gyp rebuild
125```
126
127This should rebuild the driver successfully if you have everything set up correctly.
128
129### Other possible issues
130
131Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node 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).
132
133Another thing is to ensure your user has write permission to wherever the node modules are being installed.
134
135QuickStart
136==========
137The quick start guide will show you how to setup 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 we encourage reading the tutorials.
138
139Create the package.json file
140----------------------------
141Let's create a directory where our application will live. In our case we will put this under our projects directory.
142
143```
144mkdir myproject
145cd myproject
146```
147
148Enter the following command and answer the questions to create the initial structure for your new project
149
150```
151npm init
152```
153
154Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init`
155
156```
157{
158  "name": "myproject",
159  "version": "1.0.0",
160  "description": "My first project",
161  "main": "index.js",
162  "repository": {
163    "type": "git",
164    "url": "git://github.com/christkv/myfirstproject.git"
165  },
166  "dependencies": {
167    "mongodb": "~2.0"
168  },
169  "author": "Christian Kvalheim",
170  "license": "Apache 2.0",
171  "bugs": {
172    "url": "https://github.com/christkv/myfirstproject/issues"
173  },
174  "homepage": "https://github.com/christkv/myfirstproject"
175}
176```
177
178Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies.
179
180```
181npm install
182```
183
184You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory.
185
186Booting up a MongoDB Server
187---------------------------
188Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**).
189
190```
191mongod --dbpath=/data --port 27017
192```
193
194You should see the **mongod** process start up and print some status information.
195
196Connecting to MongoDB
197---------------------
198Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver.
199
200First let's add code to connect to the server and the database **myproject**.
201
202```js
203var MongoClient = require('mongodb').MongoClient
204  , assert = require('assert');
205
206// Connection URL
207var url = 'mongodb://localhost:27017/myproject';
208// Use connect method to connect to the Server
209MongoClient.connect(url, function(err, db) {
210  assert.equal(null, err);
211  console.log("Connected correctly to server");
212
213  db.close();
214});
215```
216
217Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console.
218
219Let's Add some code to show the different CRUD operations available.
220
221Inserting a Document
222--------------------
223Let's create a function that will insert some documents for us.
224
225```js
226var insertDocuments = function(db, callback) {
227  // Get the documents collection
228  var collection = db.collection('documents');
229  // Insert some documents
230  collection.insertMany([
231    {a : 1}, {a : 2}, {a : 3}
232  ], function(err, result) {
233    assert.equal(err, null);
234    assert.equal(3, result.result.n);
235    assert.equal(3, result.ops.length);
236    console.log("Inserted 3 documents into the document collection");
237    callback(result);
238  });
239}
240```
241
242The insert command will return a results object that contains several fields that might be useful.
243
244* **result** Contains the result document from MongoDB
245* **ops** Contains the documents inserted with added **_id** fields
246* **connection** Contains the connection used to perform the insert
247
248Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback.
249
250```js
251var MongoClient = require('mongodb').MongoClient
252  , assert = require('assert');
253
254// Connection URL
255var url = 'mongodb://localhost:27017/myproject';
256// Use connect method to connect to the Server
257MongoClient.connect(url, function(err, db) {
258  assert.equal(null, err);
259  console.log("Connected correctly to server");
260
261  insertDocuments(db, function() {
262    db.close();
263  });
264});
265```
266
267We can now run the update **app.js** file.
268
269```
270node app.js
271```
272
273You should see the following output after running the **app.js** file.
274
275```
276Connected correctly to server
277Inserted 3 documents into the document collection
278```
279
280Updating a document
281-------------------
282Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**.
283
284```js
285var updateDocument = function(db, callback) {
286  // Get the documents collection
287  var collection = db.collection('documents');
288  // Update document where a is 2, set b equal to 1
289  collection.updateOne({ a : 2 }
290    , { $set: { b : 1 } }, function(err, result) {
291    assert.equal(err, null);
292    assert.equal(1, result.result.n);
293    console.log("Updated the document with the field a equal to 2");
294    callback(result);
295  });  
296}
297```
298
299The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method.
300
301```js
302var MongoClient = require('mongodb').MongoClient
303  , assert = require('assert');
304
305// Connection URL
306var url = 'mongodb://localhost:27017/myproject';
307// Use connect method to connect to the Server
308MongoClient.connect(url, function(err, db) {
309  assert.equal(null, err);
310  console.log("Connected correctly to server");
311
312  insertDocuments(db, function() {
313    updateDocument(db, function() {
314      db.close();
315    });
316  });
317});
318```
319
320Delete a document
321-----------------
322Next lets delete the document where the field **a** equals to **3**.
323
324```js
325var deleteDocument = function(db, callback) {
326  // Get the documents collection
327  var collection = db.collection('documents');
328  // Delete document where a is 3
329  collection.deleteOne({ a : 3 }, function(err, result) {
330    assert.equal(err, null);
331    assert.equal(1, result.result.n);
332    console.log("Removed the document with the field a equal to 3");
333    callback(result);
334  });
335}
336```
337
338This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient
339.connect** callback function.
340
341```js
342var MongoClient = require('mongodb').MongoClient
343  , assert = require('assert');
344
345// Connection URL
346var url = 'mongodb://localhost:27017/myproject';
347// Use connect method to connect to the Server
348MongoClient.connect(url, function(err, db) {
349  assert.equal(null, err);
350  console.log("Connected correctly to server");
351
352  insertDocuments(db, function() {
353    updateDocument(db, function() {
354      deleteDocument(db, function() {
355        db.close();
356      });
357    });
358  });
359});
360```
361
362Finally let's retrieve all the documents using a simple find.
363
364Find All Documents
365------------------
366We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query.
367
368```js
369var findDocuments = function(db, callback) {
370  // Get the documents collection
371  var collection = db.collection('documents');
372  // Find some documents
373  collection.find({}).toArray(function(err, docs) {
374    assert.equal(err, null);
375    assert.equal(2, docs.length);
376    console.log("Found the following records");
377    console.dir(docs);
378    callback(docs);
379  });
380}
381```
382
383This query will return all the documents in the **documents** collection. Since we deleted a document the total
384documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback.
385
386```js
387var MongoClient = require('mongodb').MongoClient
388  , assert = require('assert');
389
390// Connection URL
391var url = 'mongodb://localhost:27017/myproject';
392// Use connect method to connect to the Server
393MongoClient.connect(url, function(err, db) {
394  assert.equal(null, err);
395  console.log("Connected correctly to server");
396
397  insertDocuments(db, function() {
398    updateDocument(db, function() {
399      deleteDocument(db, function() {
400        findDocuments(db, function() {
401          db.close();
402        });
403      });
404    });
405  });
406});
407```
408
409This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest.
410
411## Next Steps
412
413 * [MongoDB Documentation](http://mongodb.org/)
414 * [Read about Schemas](http://learnmongodbthehardway.com/)
415 * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)