first step
Download mongodb module using npm
The second step
Import background mongodb module
Note: The module will be introduced first find their own folder node_modules modules, and if not, then go global (node installation directory)
let http = require("http");
let mongodb = require ( 'mongodb'); // import module mongodb
= MongoClient the let mongodb.MongoClient; // create a connection to the database objects
May be connected to the database after the operation of the database in the background
Background services natively written, the code interpretation
The require HTTP = the let ( "HTTP" ); // import modules mongodb the let mongodb = The require ( 'mongodb'); // module introduced will first find their own folder node_modules modules, if not, go to to find the global (node installation directory) // Create a connection to the database objects the let MongoClient = mongodb.MongoClient; the let Server = http.createServer (); server.on ( "Request", (REQ, RES) => { the let database_url = "MongoDB: // localhost: 27017 /"; // address database of the let database_name = "School"; // name of the database the let URL database_url + = database_name; // address database name database plus MongoClient.connect (url, ( ERR, DB) =>{// connect to the database // err an error message when the database connection failure err will have value db is an instance of the data after the connection is successful, all the operations are carried out to complete in this example IF (err) { console.log ( 'database connection failure " ); return ; } the console.log ( ' connection success' ); var obj = {" name ":" to Bob "," age ": 120, " hobby ": [" sleep a ", "eat A"], "Score": { "Yuwen": 590 is, "shuxue": 800 }} db.collection ( . "Student") insertMary (obj, (ERR, Result) => {// the school database collection, student data inserting an IF (ERR) { Console.log ( 'insert fails' ); return ; } The console.log (Result); // an object, which has about databases, and methods for inserting data and attributes res.end (result.toString ())
db.Close (); // db.Close (); // Close the database each time a database operation after the completion of use, be closed
});
});
}) server.listen(3000);
Related methods CRUD
Database may have a plurality of sets, a set can have a plurality of data, a set of array, a plurality of data object format (JSON) memory
db.collection ( "collection name") method, if the database does not have the set, then the additions and deletions to change search time will be added by default collection
Insert multiple data
db.collection ( "collection name") .insertMany (inserted data (target format), function (ERR, Result) { IF (ERR) the throw ERR; db.Close (); // Close the operation of the database });
Insert a data
db.collection ( "collection name"). insertOne (data insertion (target format), function (ERR, RES) { IF (ERR) the throw ERR; the console.log ( "document into success" ); db.Close () ; });
Query data
. db.collection ( "collection name") Find (Find data (object)) toArray (. function (ERR, Result) { // return the found data IF (ERR) the throw ERR; the console.log (Result); // return data conforming to find to find the object, an array of packet objects db.Close (); });
Update data (modifying data)
Update a
. db.collection ( "Site") updateOne (replaced data (objects), the updated data (objects), function (ERR, RES) { IF (ERR) the throw ERR; the console.log ( "Document successfully updated" ) ; db.Close (); });
Note: The modification data may only be modified set of data for a partial data
Update multiple
var whereStr = { "type": 'EN'}; // query var updateStr = { $ SET : { "URL": "https://www.runoob.com" }}; dbo.collection (set name ) .updateMany (whereStr, updateStr, function (ERR, RES) { IF (ERR) the throw ERR; the console.log (res.result.nModified + "document is updated article" ); //result.nModified is a number of updates. db.Close (); });
$ Set if not found, it will create the corresponding data, insert set
Will be replaced with $ unset $ set to be updated, it will delete the field
delete data
Delete conditions of the first data
db.collection (collection name). deleteOne (conditions to find (the object), function (ERR, obj) { IF (ERR) the throw ERR; console.log ( "Document deleted successfully" ); db.Close (); }) ;
Delete multiple data
Eligible delete all data
. db.collection (collection name) deleteMany (search conditions (objects), function (ERR, obj) { IF (ERR) the throw ERR; console.log (obj.result.n + "article document was deleted" ); db. Close (); });
Queries page
dbo.collection (set name) .find (). Skip (2). limit (2) .toArray ( function (ERR, Result) { IF (ERR) the throw ERR; the console.log (Result); // Result Returning to INQUIRY after the processed data tab db.Close (); });
Skip all the data (num) to the query, the skip num returns a query result of data
All data limit (num) queried, returns num of data
Paging query can be used when the data is too large, partially Find
DAO layer appreciated and packaging
DAO layer reason
Originated in java, java dao can write a very large
Make a special connection to the database layer, and then exposed interface to access background
DAO logic
DAO layer design is first designed interface DAO, can then call this interface module for processing data traffic,
Without concern for this interface implementation class is which class, it is very clear structure, data source DAO layer configuration.
DAO layer effect
The main job is to do data persistence layer, is responsible for liaison with some of the tasks are encapsulated in this database
In short: it is obtained by introduction of the module, the package method of operation of the database will then exposed interface for background operation is acquired in the intermediate layer and the intermediate database
In the node, DAO layer also can write very large.
The following is a connection node DAO layer of mongodb
var MongoDB = the require ( "MongoDB" ); var MongoClient = mongodb.MongoClient; function _connectDB (the callback) { the let database_url = "MongoDB: // localhost: 27017 /"; // address database of the let database_name = "Data"; / / database name the let URL database_url + = database_name; MongoClient.connect (URL, function (ERR, DB) { IF (ERR) { the callback (ERR, null ); return ; } the callback (ERR, DB); }) } // // insert data interfaces exposed exports.insertOne = function(collectionName,json,callback){ _connectDB(function(err,db){ db.collection(collectionName).insertOne(json, (err, result) => { // if(err){ // callback(err,null) // return; // } callback(err,result); db.close(); }); }) } // 删除的接口 exports.deleteMany = function(collectionName,json,callback){ _connectDB(function(err,db){ db.collection (collectionName) .deleteMany (JSON, function (ERR, Result) { the callback (ERR, Result); db.Close (); }) }) } // update data exports.updateMany = function (collectionName, json1, json2, the callback) { _connectDB ( function (ERR, DB) { db.collection (collectionName) .updateMany (json1, json2, function (ERR, Result) { the callback (ERR, Result); db.Close (); }) } ) }
// Let's say I do not need pagination, page parameters can not need to pass exports.find = function (collectionName, JSON, C, D) { var Result = []; IF (== The arguments.length. 3) { // this time is not required paging var the callback = C; var limitnum = 0 ; var skipnum = 0 ; } the else IF (== the arguments.length. 4 ) { // assuming c is a parameter passed in the object { // pageamount: 10, // Page: 0 // } var the callback = D; // Finally, it is a callback function var args = C; // paged conditions // article number omitted varargs.page || * = args.pageamount skipnum 0 (ERR) {; // the Number Found var limitnum args.pageamount || = 0 ; // Sort var Sort args.sort || = {}; } the else { the throw new new Error ( 'find the number of arguments must be three or four ' ) return ; } _connectDB ( function (ERR, DB) { var Cursor = db.collection (collectionName) .find (JSON) .skip (skipnum) .limit (limitnum) .sort (Sort) cursor.each ( function (ERR, DOC) { IF the callback (ERR, null ); db.close(); return } if(doc!=null){ result.push(doc); }else{ callback(null,result); db.close() } }) }) }
Interpretation paging query package
collectionName: need to query data set name
json: object search conditions
C, D: two cases
1. If no pagination queries, D parameters do not need, and C parameters are passed in the callback
2. paged query, the incoming C, the object is to query paging, D callback function
at this time should be in the form of a c incoming objects, rather than numeric
// C object templates
C = {
pageamount: 10, // skip the Number
number of display @ 0: page
}
Paging query distinguish
Front page fake background to obtain all the data from the database all over, and then to the intact front desk to the page based on all the data.
Background false paging backstage to get all of the data all come from the database and front-end based on the parameters passed to it, returned to the front end of a few data.
Really pages, so do things to the database, reducing the transmission of content.