NODE13---node using MongoDB

Source: Internet
Author: User
Tags assert mongoclient

01.js

/** * The first background language is ASP (Microsoft),*/varExpress = Require ("Express");//Database ReferencevarMongoclient = require (' MongoDB '). mongoclient;varassert = require (' assert ');//Debug: Assert.equal (NULL,ERR); error stop executing the following statementvarApp =Express ();//The address of the database connection, the last slash indicates the database name, and the database does not exist createsvarShujukuurl = ' Mongodb://localhost:27017/itcast '; App.get ("/",function(req,res) {//Connect to the database, which is an asynchronous operationMongoclient.connect (Shujukuurl,function(err, db) {if(Err) {Res.send ("Database connection Failed"); return; } res.write ("Congratulations, the database has been successfully connected \ n"); Db.collection ("Teacher"). Insertone ({"name": "Haha"},function(err,result) {if(Err) {Res.send ("Database Write Failed"); return; } res.write ("Congratulations, the data has been successfully inserted");            Res.end (); //Close the databaseDb.close ();    }); });}); App.listen (3000);

02.js

/** * Created by Danny on 2015/9/23 17:24.*/varExpress = Require ("Express");varMongoclient = require (' MongoDB '). mongoclient;varassert = require (' Assert ');varApp =Express (); App.set ("View Engine", "Ejs");//The address of the database connection, and the last slash indicates the database namevarShujukuurl = ' Mongodb://localhost:27017/itcast '; App.get ("/",function(req,res) {//Connect to the database first, and all operations on the database are written in his callback function. Mongoclient.connect (Shujukuurl,function(err, db) {if(err) {//res.write ("Database connection Failed");            return; }        //Res.write ("Congratulations, the database has been successfully connected \ n");        //query database, cursor cursor, cursor can traverse with each method        //each time a document is represented        varresult = []; varcursor = db.collection (' Teacher '). find (); Cursor.each (function(err, doc) {if(err) {//res.write ("Cursor traversal error");                return; }            if(Doc! =NULL) {Result.push (doc); } Else {                //Console.log (result);                //Traverse CompleteDb.close (); Res.render ("Index",{                    "Result": result});    }        }); });}); App.get ("/add",function(req,res) {Res.render ("Add");//Add Page}); App.get ("/tijiao",function(req,res) {//Get Parameters    varName =Req.query.name; varAge =Req.query.age; varYuwenchengji =Req.query.yuwenchengji; varShuxuechengji =Req.query.shuxuechengji; Mongoclient.connect (Shujukuurl,function(err, db) {if(Err) {Console.log ("Database connection Failed"); return; } db.collection ("Teacher"). Insertone ({"Name": Name,"Age": Age,"Score" : {                "Shuxue": Shuxuechengji,"Yuwen": Yuwenchengji}},function(err,result) {if(Err) {Console.log ("Database Write Failed"); return; } res.send ("Congratulations, the data has been successfully inserted");            Res.end (); //Close the databaseDb.close ();    }); });}); App.listen (3000);

03.js

varExpress = Require ("Express");varApp =Express ();varMongoclient = require (' MongoDB '). Mongoclient;app.get ("/",function(req,res) {//The URL is the address of the database. /Represents a database    //If the database does not exist, it does not matter, the program will help you to automatically create a database    varurl = ' Mongodb://localhost:27017/haha '; //Connect to the database, each user requests to open the database and then close the database (PHP also shuts down the database every time the database is opened)Mongoclient.connect (URL,function(err, db) {//The callback function indicates the success of the connection, and the DB parameter is the database entity on the connection.        if(Err) {Console.log ("Database connection Failed"); return; } console.log ("Database connection succeeded"); //Insert Data, if the collection does not exist, it does not matter, the program will help you createDb.collection (' student '). Insertone ({//the ID that was generated before the time stamp is the machine code, the world's only"Name": "Haha",            "Age": parseint (Math.random () * 100 + 10)        }, function(err, result) {if(Err) {Console.log ("Insert Failed"); return; }            //after inserting, result indicates insert result.             //Console.log (result);res.send (Result);        Db.close ();    }); });}); App.listen (3000);

Paging:

first, the database paging, think of our Baidu hundreds of Ajax cases, at that time called the Baidu JSON, there is a parameter called page=3, the resulting JSON is not the same. This is the paging, we want to find all the news, but it is on the 3rd page of the news. Then there are two ways:1the wrong approach: that is, all the result is read to the array, then the data operation, paging;2The right thing to do is to actually read only so much content in the database. Wrong, we're trying to read all the data every time, but it's a lot of overhead. 1varA = [];2 Db.find ("Student", {},function(err,result) {3 for(vari = ten * page; I < * (page + 1); i++){4A.push (Result[i]);5        }6Res.send (a);7}); So, MongoDB provides a silly two functions. Limit (): Read the number of bars, skip (): Skip how many joins, the first is page=0. 10 articles per page, so the query statement for the current page 1db.student.find ({}). Limit (). Skip (page*10How do I get the total data? Shell 1db.student.stats (). Count;

NODE13---node using MongoDB

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.