PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/mongodb/README.md

https://gitlab.com/vasuvanka/hphrs
Markdown | 415 lines | 315 code | 100 blank | 0 comment | 0 complexity | 42e864d00ba270acee7815d36b1a8062 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. [![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native)
  3. [![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)
  4. [![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
  5. # Description
  6. 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.
  7. ## MongoDB Node.JS Driver
  8. | what | where |
  9. |---------------|------------------------------------------------|
  10. | documentation | http://mongodb.github.io/node-mongodb-native/ |
  11. | api-doc | http://mongodb.github.io/node-mongodb-native/2.1/api/ |
  12. | source | https://github.com/mongodb/node-mongodb-native |
  13. | mongodb | http://www.mongodb.org/ |
  14. ### Blogs of Engineers involved in the driver
  15. - Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com>
  16. ### Bugs / Feature Requests
  17. Think youve found a bug? Want to see a new feature in node-mongodb-native? Please open a
  18. case in our issue management tool, JIRA:
  19. - Create an account and login <https://jira.mongodb.org>.
  20. - Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>.
  21. - Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
  22. Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
  23. Core Server (i.e. SERVER) project are **public**.
  24. ### Questions and Bug Reports
  25. * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native
  26. * jira: http://jira.mongodb.org/
  27. ### Change Log
  28. http://jira.mongodb.org/browse/NODE
  29. # Installation
  30. The 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.
  31. ## MongoDB Driver
  32. Given 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.
  33. ```
  34. npm install mongodb --save
  35. ```
  36. This will download the MongoDB driver and add a dependency entry in your `package.json` file.
  37. ## Troubleshooting
  38. The MongoDB driver depends on several other packages. These are.
  39. * mongodb-core
  40. * bson
  41. * kerberos
  42. * node-gyp
  43. 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 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.
  44. {{% note class="important" %}}
  45. 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.
  46. {{% /note %}}
  47. ### Diagnosing on UNIX
  48. If you dont have the build essentials it wont 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 whats missing is by trying to build the kerberos project. You can do this by performing the following steps.
  49. ```
  50. git clone https://github.com/christkv/kerberos.git
  51. cd kerberos
  52. npm install
  53. ```
  54. If 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.
  55. ```
  56. npm install -g node-gyp
  57. ```
  58. If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command.
  59. ```
  60. cd yourproject
  61. npm install mongodb --save
  62. ```
  63. If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
  64. ```
  65. npm --loglevel verbose install mongodb
  66. ```
  67. This will print out all the steps npm is performing while trying to install the module.
  68. ### Diagnosing on Windows
  69. A known compiler tool chain known to work for compiling `kerberos` on windows is the following.
  70. * Visual Studio c++ 2010 (do not use higher versions)
  71. * Windows 7 64bit SDK
  72. * Python 2.7 or higher
  73. Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp.
  74. ```
  75. npm install -g node-gyp
  76. ```
  77. Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo.
  78. ```
  79. git clone https://github.com/christkv/kerberos.git
  80. cd kerberos
  81. npm install
  82. node-gyp rebuild
  83. ```
  84. This should rebuild the driver successfully if you have everything set up correctly.
  85. ### Other possible issues
  86. Your 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).
  87. Another thing is to ensure your user has write permission to wherever the node modules are being installed.
  88. QuickStart
  89. ==========
  90. The 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.
  91. Create the package.json file
  92. ----------------------------
  93. Let's create a directory where our application will live. In our case we will put this under our projects directory.
  94. ```
  95. mkdir myproject
  96. cd myproject
  97. ```
  98. Enter the following command and answer the questions to create the initial structure for your new project
  99. ```
  100. npm init
  101. ```
  102. Next 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`
  103. ```
  104. {
  105. "name": "myproject",
  106. "version": "1.0.0",
  107. "description": "My first project",
  108. "main": "index.js",
  109. "repository": {
  110. "type": "git",
  111. "url": "git://github.com/christkv/myfirstproject.git"
  112. },
  113. "dependencies": {
  114. "mongodb": "~2.0"
  115. },
  116. "author": "Christian Kvalheim",
  117. "license": "Apache 2.0",
  118. "bugs": {
  119. "url": "https://github.com/christkv/myfirstproject/issues"
  120. },
  121. "homepage": "https://github.com/christkv/myfirstproject"
  122. }
  123. ```
  124. Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies.
  125. ```
  126. npm install
  127. ```
  128. 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.
  129. Booting up a MongoDB Server
  130. ---------------------------
  131. Let'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**).
  132. ```
  133. mongod --dbpath=/data --port 27017
  134. ```
  135. You should see the **mongod** process start up and print some status information.
  136. Connecting to MongoDB
  137. ---------------------
  138. Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver.
  139. First let's add code to connect to the server and the database **myproject**.
  140. ```js
  141. var MongoClient = require('mongodb').MongoClient
  142. , assert = require('assert');
  143. // Connection URL
  144. var url = 'mongodb://localhost:27017/myproject';
  145. // Use connect method to connect to the Server
  146. MongoClient.connect(url, function(err, db) {
  147. assert.equal(null, err);
  148. console.log("Connected correctly to server");
  149. db.close();
  150. });
  151. ```
  152. Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console.
  153. Let's Add some code to show the different CRUD operations available.
  154. Inserting a Document
  155. --------------------
  156. Let's create a function that will insert some documents for us.
  157. ```js
  158. var insertDocuments = function(db, callback) {
  159. // Get the documents collection
  160. var collection = db.collection('documents');
  161. // Insert some documents
  162. collection.insertMany([
  163. {a : 1}, {a : 2}, {a : 3}
  164. ], function(err, result) {
  165. assert.equal(err, null);
  166. assert.equal(3, result.result.n);
  167. assert.equal(3, result.ops.length);
  168. console.log("Inserted 3 documents into the document collection");
  169. callback(result);
  170. });
  171. }
  172. ```
  173. The insert command will return a results object that contains several fields that might be useful.
  174. * **result** Contains the result document from MongoDB
  175. * **ops** Contains the documents inserted with added **_id** fields
  176. * **connection** Contains the connection used to perform the insert
  177. Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback.
  178. ```js
  179. var MongoClient = require('mongodb').MongoClient
  180. , assert = require('assert');
  181. // Connection URL
  182. var url = 'mongodb://localhost:27017/myproject';
  183. // Use connect method to connect to the Server
  184. MongoClient.connect(url, function(err, db) {
  185. assert.equal(null, err);
  186. console.log("Connected correctly to server");
  187. insertDocuments(db, function() {
  188. db.close();
  189. });
  190. });
  191. ```
  192. We can now run the update **app.js** file.
  193. ```
  194. node app.js
  195. ```
  196. You should see the following output after running the **app.js** file.
  197. ```
  198. Connected correctly to server
  199. Inserted 3 documents into the document collection
  200. ```
  201. Updating a document
  202. -------------------
  203. Let'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**.
  204. ```js
  205. var updateDocument = function(db, callback) {
  206. // Get the documents collection
  207. var collection = db.collection('documents');
  208. // Update document where a is 2, set b equal to 1
  209. collection.updateOne({ a : 2 }
  210. , { $set: { b : 1 } }, function(err, result) {
  211. assert.equal(err, null);
  212. assert.equal(1, result.result.n);
  213. console.log("Updated the document with the field a equal to 2");
  214. callback(result);
  215. });
  216. }
  217. ```
  218. The 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.
  219. ```js
  220. var MongoClient = require('mongodb').MongoClient
  221. , assert = require('assert');
  222. // Connection URL
  223. var url = 'mongodb://localhost:27017/myproject';
  224. // Use connect method to connect to the Server
  225. MongoClient.connect(url, function(err, db) {
  226. assert.equal(null, err);
  227. console.log("Connected correctly to server");
  228. insertDocuments(db, function() {
  229. updateDocument(db, function() {
  230. db.close();
  231. });
  232. });
  233. });
  234. ```
  235. Delete a document
  236. -----------------
  237. Next lets delete the document where the field **a** equals to **3**.
  238. ```js
  239. var deleteDocument = function(db, callback) {
  240. // Get the documents collection
  241. var collection = db.collection('documents');
  242. // Insert some documents
  243. collection.deleteOne({ a : 3 }, function(err, result) {
  244. assert.equal(err, null);
  245. assert.equal(1, result.result.n);
  246. console.log("Removed the document with the field a equal to 3");
  247. callback(result);
  248. });
  249. }
  250. ```
  251. This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient
  252. .connect** callback function.
  253. ```js
  254. var MongoClient = require('mongodb').MongoClient
  255. , assert = require('assert');
  256. // Connection URL
  257. var url = 'mongodb://localhost:27017/myproject';
  258. // Use connect method to connect to the Server
  259. MongoClient.connect(url, function(err, db) {
  260. assert.equal(null, err);
  261. console.log("Connected correctly to server");
  262. insertDocuments(db, function() {
  263. updateDocument(db, function() {
  264. deleteDocument(db, function() {
  265. db.close();
  266. });
  267. });
  268. });
  269. });
  270. ```
  271. Finally let's retrieve all the documents using a simple find.
  272. Find All Documents
  273. ------------------
  274. We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query.
  275. ```js
  276. var findDocuments = function(db, callback) {
  277. // Get the documents collection
  278. var collection = db.collection('documents');
  279. // Find some documents
  280. collection.find({}).toArray(function(err, docs) {
  281. assert.equal(err, null);
  282. assert.equal(2, docs.length);
  283. console.log("Found the following records");
  284. console.dir(docs);
  285. callback(docs);
  286. });
  287. }
  288. ```
  289. This query will return all the documents in the **documents** collection. Since we deleted a document the total
  290. documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback.
  291. ```js
  292. var MongoClient = require('mongodb').MongoClient
  293. , assert = require('assert');
  294. // Connection URL
  295. var url = 'mongodb://localhost:27017/myproject';
  296. // Use connect method to connect to the Server
  297. MongoClient.connect(url, function(err, db) {
  298. assert.equal(null, err);
  299. console.log("Connected correctly to server");
  300. insertDocuments(db, function() {
  301. updateDocument(db, function() {
  302. deleteDocument(db, function() {
  303. findDocuments(db, function() {
  304. db.close();
  305. });
  306. });
  307. });
  308. });
  309. });
  310. ```
  311. This 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.
  312. ## Next Steps
  313. * [MongoDB Documentation](http://mongodb.org/)
  314. * [Read about Schemas](http://learnmongodbthehardway.com/)
  315. * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)