MongoDB Native node. js Driver

Source: Internet
Author: User
Tags app service create mongodb findone install mongodb log log modifier mongodb server safe mode

Write in front

The recent reading of the node. JS Learning Guide does not introduce much to MongoDB, but for a front-end developer, even if you haven't used the database, you can understand and use it well.

A very good introduction to the Book of node. js, and I've kept him where I can reach. --mike Amundsen

The MongoDB Native node. JS Driver module is the driver for MongoDB's own node, which is basically consistent with the MongoDB instructions issued by the MongoDB client.

Ready to start--

1, first we should ensure that our MongoDB database local installation can run normally, if the installation process to encounter problems can be easily referred to my previous blog (window under the configuration and installation of MongoDB)

2. Then we need to create a new project <nodeLearn> mkdir Nodelearn , creating a App.js file as the project startup file.

3. Then we need to install MongoDB Native node. js Driver: npm Install MongoDB in the project file 

4. Start

1) Introduce the module and use MongoDB driver to create MongoDB. Server object to establish a connection to the database:

var mongodb = require (' MongoDB ')  varnew MongoDB. Server (' localhost ', 27017,{auto_reconnect:true })

Note: The first two parameters of the server constructor are the localhost and 27017 default ports, the third parameter is optional, and the option is set to true, indicating that if the connection is disconnected driver will automatically reconnect (there is also a parameter pollsize, which determines the number of concurrent TCP connections, I have not yet touched = =).

2) Use MongoDB. DB Object Creation Database

var New MongoDB. Db (' mydb ', server)

Note: The second parameter indicates the creation of a connected MongoDB server

Mongodb Collection

There is no concept of tables in MongoDB and we need a collection.

1. Create a Collection collection object in the database

Db.createcollection (' mycollection ',function(err,collection) {})
Db.collection (' mycollection ',function(err,collection) {})

Note: There are some differences between using create and not using Create, which is created immediately, and if you use the CreateCollection method for an already existing collection, you can also access the collection-driver directly and not overwrite it. Do not use create and the actual collection is not created.

2. Completely destroy a collection in the database

Db.dropcollection (' mycollection ',function(err,result) {})
Add data to Collection

Before adding data, we need to know that there is a mapping between the node MongoDB driver and the MongoDB data type (but I don't understand the processing mechanism behind the data transformation, so here's a hint for a blog post)

Add Data:

1, first remove the existing collection document with the Remove method to prevent the creation of the failure,

2. Insert data using the Insert method (accept three parameters, Safe mode, keepgoing "Insert failed to continue execution", serializefunctions "serialization")

Here we can already connect to our MongoDB database, and add documents, this is for a sophomore front-end development of small partners is excited, so that the night does not sleep the disturbance of the nervous-

1 varMongoDB = require (' MongoDB ');2 3 varServer =NewMongodb. Server (' localhost ', 27017, {auto_reconnect:true});4 vardb =NewMongodb. Db (' Exampledb ', server);5 6Db.open (function(err, db) {7     if(!err) {8Db.collection (' Widgets ',function(Err, collection) {9             //Delete data from the Exampledb database widgets collectionTenCollection.remove (NULL, {safe:true},function(err, result) { One                 if(!err) { AConsole.log (' Result of remove ' +result); -                     //Create two data -                     varWidget1 = {id:1, title: ' First great widget ', desc: ' Greatest widget of all ', price:14.99}; the                     varWidget2 = { -Id:2, -Title: ' Second Great widget ', -Desc: ' Second greatest widget of all ', +price:29.99 -                     }; + Collection.insert (WIDGET1); ACollection.insert (Widget2, {safe:true},function(err, result) { at                         if(err) { - Console.log (Err) -}Else { -Collection.find (). ToArray (function(Err, docs) { - Console.log (docs); -                                 //Close the database in db.close (); -                             }); to                         } +                     }) -                 } the             }) *         }) $     }Panax Notoginseng});

To enter the project file, we start the app service via the node command: node app ,

Of course, if you want to avoid the tedious need to restart the service with the node command after each modification, you can use supervisor to install the global using the npm install supervisor-g and use the Supervisor command instead of node , you do not need to restart the service with the node command every time after you modify the file

So let's look at the results at the command line--

    

Then we see the results of the data in the MongoDB database: (If you have configured the MONGO environment variable, open cmd as an administrator, start MongoDB with the MONGO command)

    

You'll see that the two data we want is also included in the database widgets document.

If the document data is processed in bulk, we need to set keepgoing to true as much as possible.

Implementing query data

There are four ways to query data for MongoDB Native node. JS driver: Find (), FindOne (), Findandremove (), findandmodify ()

FindOne () and find () support the following three parameters: query data, optional parameters, callback functions. (Optional parameters and callback functions are optional, and the optional values for both options are very large, but most queries use only a small subset of the option values)

Common sort (document sort, 1 inverted, 1 positive sort),

Field (query statement and return field),

Skip (Skip N documents for page skipping)

Hint (tells the database to use a specific index)

Returnkey (returns the index key only)

Comment (Add a description to the log log file for the query)

Showdiscloc (Displays the results in the disk location) ...

These option values can also be used under MONGO for some manipulation of the data

1, Next we use Find () query and return the contents of our database, you can directly use the ToArray () method to convert the results to an array

2. Use optional Value field to filter, {fields:{type=0}} set to zero for fields other than type, 1 instead

Collection.find ({type= "A"},{fields:{type=0}}). ToArray (function(err,docs) {    if (Err) {        console.log (err)    }else{        console.log (docs);          // Close Database Link          db.close ();     }})

Let's find all the type a, and return this data (without the Type field). However, it is important to note that we are set to 1, not just the Type field, the system-generated unique identifier that is _id always appears in the query results

updating, deleting documents

Ways to modify or delete a document: Update the document: updating () or upserts (adding a document if it does not exist), removing the document remove (), finding and modifying or deleting a document findandmodify (), Find and delete a document Findandremove ()

The most essential difference between the Update/remove and the last two methods is that the latter two methods return the manipulated document

Use the $set modifier instead of field, $set modifier so that only the field that is passed as an attribute to the modifier is modified

1 varMongoDB = require (' MongoDB ');2 3 varServer =NewMongodb. Server (' localhost ', 27017, {auto_reconnect:true});4 vardb =NewMongodb. Db (' Exampledb ', server);5 6Db.open (function(err, db) {7     if(!err) {8Db.collection (' Widgets ',function(Err, collection) {9             //Update DataTenCollection.update ({id:2}, {$set: {title: "Super Bad Widget"}}, {safe:true},function(err, result) { One                 if(err) { A Console.log (Err) -}Else { - Console.log (result); the                     //querying the Update database -Collection.findone ({id:2},function(err, doc) { -                         if(!err) { - Console.log (DOC); +                             //Close the database - db.close (); +                         } A                     }) at                 } -             }) -         }) -     } -});

The updated database has changed

Write it in the back.

Using the MongoDB Native node. JS driver module, the driver instructions are basically consistent with the MongoDB client, and if you are interested in the original driver module like me, then this Nodejs driver official website will certainly help you.

While the original driver provides a connection to the database but lacks a higher level of abstraction, it is cumbersome, so sometimes you need to use a mongoose-like ODM,

Built on MongoDB, Mongoose provides schema, model, and document objects that are more convenient to use.

Next time I'll summarize the connection using Express + Mongoose to establish a database

MongoDB Native node. js Driver

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.