The seventh chapter recommends 4 hours of study time 10 chapters
How to learn: read it in detail and implement the relevant code manually
Learning Goals : This tutorial will teach you to install node, build servers, Express, MySQL, MongoDB, write background business logic, write interfaces, and finally complete a complete project backstage, a total of 10 days is expected.
node. js Operation Mangodb
Create a folder for placing today's files, NPM init initializes, and creates demo1.js for writing node code
Install the MongoDB control module to a local using NPM install MongoDB
Write the following operation code in Demo1.js
1 varMONGO = require ("MongoDB");//Introducing the MongoDB module2 varassert = require ("assert");//introducing the Assertion module3 4 varMongoclient = MONGO. Mongoclient;//Open Service5 6 varUrls = "Mongodb://localhost:27017/demo2";//The URL store is placed in the connection pool. 7 8Mongoclient.connect (Urls,function(ERR,DB) {//Get Connections9Assert.equal (NULL, err);//use assertion module instead of previous if judgmentTen One A //Inserting Data -Db.collection ("T1"). Insert ({"name": "Xiaoming"},function(Err,result) {//connect to the database and pass in the collection using Parameters -Assert.equal (NULL, err); the Console.log (result); - db.close (); - }); - + -});
Code Explanation:
1 rows and 2 rows introduced the required two modules, 4 rows to open the server,
6 line is the address of the URL, the general default installation of the address and port is "mongodb://localhost:27017", the following Demo2 is the name of my MongoDB database (you replace the database you created)
8 rows are based on the URL declared above to establish a connection to the database, the Connect method has two parameters, 1, the connected database address, 2, callback function, two parameters of the callback function to send the error, and the correct case to return the database link, we can operate on this link.
Note: The link here is the place where beginners often error, if the error, to confirm the address and database name is wrong, make sure that their database has the corresponding library name.
Focus on the next 13 lines, here is the operation of node insert database, db.collection ("T1") means to get the table that needs operation, insert is Insert method, method receives two parameters, 1, insert content, 2, callback function, callback function two parameters indicate send error, And the results returned in the correct case.
15 Line Print error results, 16 lines close and Database link (if the browser crashes)
Execute demo1.js. Successful results are obtained (n of the dash indicates success 1)
Querying the database, you can see the newly added data
Look up: The Find method, the JSON passed in to find the filter (if not passed, query all), after the toarray is to manipulate the data into an array format we can recognize
The remainder of the operation, in addition to the central data manipulation section of the code, the rest of the code is the same.
1 varMONGO = require ("MongoDB");//Introducing the MongoDB module2 varassert = require ("assert");//introducing the Assertion module3 4 varMongoclient = MONGO. Mongoclient;//Open Service5 6 varUrls = "Mongodb://localhost:27017/demo2";//The URL store is placed in the connection pool. 7 8Mongoclient.connect (Urls,function(ERR,DB) {//Get Connections9Assert.equal (NULL, err);//use assertion module instead of previous if judgmentTen One A //Find Data -Db.collection ("T1"). Find ({"name": "Xiaoming"}). ToArray (function(err,result) { -Assert.equal (NULL, err); the Console.log (result); - db.close (); - }) - + -});
Run, successfully finds the data inserted in the previous step
Delete using Deleteone to delete a piece of data, two parameter 1, delete lookup JSON 2, callback function
1 varMONGO = require ("MongoDB");//Introducing the MongoDB module2 varassert = require ("assert");//introducing the Assertion module3 4 varMongoclient = MONGO. Mongoclient;//Open Service5 6 varUrls = "Mongodb://localhost:27017/demo2";//The URL store is placed in the connection pool. 7 8Mongoclient.connect (Urls,function(ERR,DB) {//Get Connections9Assert.equal (NULL, err);//use assertion module instead of previous if judgmentTen One //Delete Data ADb.collection ("T1"). Deleteone ({"Name": "Xiaoming"},function(Err,result) {//connect to the database and pass in the collection using Parameters -Assert.equal (NULL, err); - Console.log (result); the db.close (); - }); - -});
execution, the result of success
Query database Discovery xiaoming that data was deleted.
Modified: Using the Update method, including three parameters, 1, query criteria, 2, modified fields and modifiers, 3, callback function
varMONGO = require ("MongoDB");//Introducing the MongoDB modulevarassert = require ("assert");//introducing the Assertion modulevarMongoclient = MONGO. Mongoclient;//Open ServicevarUrls = "Mongodb://localhost:27017/demo2";//The URL store is placed in the connection pool. Mongoclient.connect (Urls,function(ERR,DB) {//Get ConnectionsAssert.equal (NULL, err);//use assertion module instead of previous if judgment //Modifying DataDb.collection ("T1"). Update ({"name": "Zhangsan1"},{$set: {"name": "Xiaoming"}},function(Err,result) {//connect to the database and pass in the collection using ParametersAssert.equal (NULL, err); Console.log (result); Db.close (); });});
Results of successful operation
Querying the database found that the original zhangsan1 was modified into a xiaoming
Here, the implementation of the Nodejs additions and deletions to search the MongoDB database
Package additions and deletions to the code
Create a package JS file dbhandler.js, copy the following code (encapsulated code text explanation is too difficult, here does not explain, only to introduce how to use, you may later out video tutorial, then explain the package in detail)
---Note: The database behind the URL of line 6th is replaced with the database you want to manipulate, and the rest does not change.
varMongo=require ("MongoDB");//@2.2.11varMongoclient =MONGO. mongoclient;varassert = require (' Assert ');varhost= "localhost";varPort= "27017";varUrls = ' Mongodb://localhost:27017/demo2 ';//add a piece of datavarAdd =function(DB,COLLECTIONS,SELECTOR,FN) {varCollection =db.collection (collections); Collection.insertmany ([selector],function(Err,result) {assert.equal (err,NULL); fn (result); Db.close (); });}//DeletevarDeletes =function(DB,COLLECTIONS,SELECTOR,FN) {varCollection =db.collection (collections); Collection.deleteone (Selector,function(err,result) {Try{Assert.equal (err,NULL)}Catch(e) {console.log (e); } fn (result); Db.close (); });};//FindvarFind =function(DB,COLLECTIONS,SELECTOR,FN) {varCollection =db.collection (collections); Collection.find (selector). ToArray (function(err,docs) {Try{assert.equal (err,NULL); }Catch(e) {console.log (e); Docs= []; } fn (docs); Db.close (); });}//(permission control)--not available for the time beingMongoclient.connect (Urls,function(err, db) {find (db,"Powers",NULL,function(d) {Console.log ("123s"); Console.log (d.length); });});//UpdatevarUpdates =function(DB,COLLECTIONS,SELECTOR,FN) {varCollection =db.collection (collections); Console.log (selector); Collection.updateone (selector[0],SELECTOR[1],function(Err,result) {assert.equal (err,NULL); Assert.equal (1, RESULT.RESULT.N); fn (result); Db.close (); });}//method is assigned to the operand, making it easy to invoke thevarMethodtype ={login:find, Show:find, Add:add, Getpower:find, Update:updates,Delete:d eletes, Updatepass:updates, Adduser:add, Usershow:find, Getcategory:find, Getcourse:find, Find:find, State:fi nd, Top:find, Adddirectory:find, Updatedirectory:updates, Deletedirectory:deletes, Showlist:find, showdir:find};//Master LogicModule.exports =function(REQ,RES,COLLECTIONS,SELECTOR,FN) {mongoclient.connect (Urls,function(err, db) {assert.equal (NULL, err); Console.log ("Connected correctly to server"); Methodtype[req.query.action] (DB,COLLECTIONS,SELECTOR,FN); Db.close (); });};
Use this package
Specific package usage, we will introduce in the next lesson project
Let's talk about it today, tomorrow we will explain: project creation, background data request interface writing
Follow the public number, blog updates can receive push
node. js 0 Basic Detailed tutorial (7): node. js operation MongoDB, and how to package