---restore content starts---
1, create the folder (the name arbitrarily, assuming: day05);
2. Create Node_modules folder (place dependency package)
3 npm init
. Create a file for your app by command package.json
.
4, install Express, MongoDB, install the command: NPM install Express--save and NPM install MongoDB--save, and save it to the dependency list ( hint: When you install the Node module, if you specify a --save
parameter, then this module will be added to the package.json
list of dependencies in the file dependencies
. npm install
all modules listed in the dependency list are then automatically installed by command, and if you just install express temporarily and don't want to add it to the dependency list, simply omit the --save
parameters. ):
5, the same directory to create a file test.js, with simple code to try:
The code is as follows:
var express = Require ("Express"); var App = Express (); App.get ("/",function (req,res) {res.send ("Run successfully! ");}); App.listen (3000);
6, in the cmd input "" Run in the browser input http://localhost:3000/, enter the display run successfully!.
7. Next we try to connect to the database using node. js, first start the MongoDB service (note: another cmd window): Mongod--dbpath D:\ProgramFiles\mongodb-v3.4\data\db:
8. Modify the code of the Test.js file:
var express = Require ("Express"); var App = Express (); var Mongoclient = require (' MongoDB '). mongoclient; var assert = require (' assert ');//For debug Info // Connection URLvar' mongodb:// Localhost:27017/myproject ';///connection address, slash "/myproject" means database, automatically created if not present
App.get ("/", function () {
function (Err, DB) { //Use Connect method to connect to the server
The //callback function represents what was done after the connection was successful, and DB is the database entity on the connection.
if (err) { //Assert.equal (NULL, err), err and null are compared, and if err==null is equal, the database connection succeeds.
Console.log ("Database connection failed");
return;
}
< EM id= "__mcedel" > Console.log (" connected successfully to Server ");
Db.close ();
});
Res.send ("Hello");
});
App.listen (3000);
01_ using node. js to connect MongoDB