Connecting to a database
1 varMongo=require ("MongoDB");2 varhost= "localhost";3 varport=MONGO. Connection.default_port;4 varServer=NewMongo. Server (host,port,{auto_reconnect:true});//Server server where the database is created5 vardb=NewMongo. Db ("Node-mongo-examples", Server,{safe:true});//To Create a database object6Db.open (function(ERR,DB) {//connecting to a database7 if(ERR)8 Throwerr;9 Else{TenConsole.log ("Database connection successfully established"); One db.close (); A } - }); -Db.on ("Close",function(ERR,DB) {//Close the database the if(ERR)Throwerr; - ElseConsole.log ("Successfully closed database.")); -});
Insert data:
Output data document content in console after inserting data
1 varMongo=require ("MongoDB");2 varhost= "localhost";3 varport=MONGO. Connection.default_port;4 varServer=NewMongo. Server (host,port,{auto_reconnect:true});//Server server where the database is created5 vardb=NewMongo. Db ("Node-mongo-examples", Server,{safe:true});//To Create a database object6Db.open (function(ERR,DB) {//connecting to a database7 if(ERR)8 Throwerr;9 Else{TenDb.collection ("Users",function(err,collection) { OneCollection.insert ({username: "Hope", FirstName: "Li"},function(err,docs) { A Console.log (docs); - db.close (); - }); the }); - } - }); -Db.on ("Close",function(ERR,DB) {//Close the database + if(ERR)Throwerr; - ElseConsole.log ("Successfully closed database.")); +});
Close Database Db.close ([forceclose],[callback]);
When Forceclose is true, the database is forced to close, and when the database is closed, open can no longer be used to open the database.
When Forceclose is false, the database is not forced to close, and when the database is closed, it can be opened again using open.
When Foreclose is true:
1 varMongo=require ("MongoDB");2 varhost= "localhost";3 varport=MONGO. Connection.default_port;4 varServer=NewMongo. Server (host,port,{auto_reconnect:true});//Server server where the database is created5 vardb=NewMongo. Db ("Node-mongo-examples", Server,{safe:true});//To Create a database object6Db.open (function(ERR,DB) {//connecting to a database7 if(ERR)8 Throwerr;9 Else{TenDb.collection ("Users",function(err,collection) { OneCollection.insert ({username: "Hope", FirstName: "Li"},function(err,docs) { A Console.log (docs); -Db.close (false); - }); the }); - } - }); -Db.once ("Close",function(ERR,DB) {//Close the database + if(ERR)Throwerr; - Else { +Db.open (function(err,db) { ADb.collection ("Users",function(err,collection) { atCollection.insert ({username: "three", FirstName: "Zhang"},function(err,docs) { - if(ERR)Throwerr; - Else{ - Console.log (docs); -Db.close (true); - } in }) - }); to }); + } -});
The most basic example of node manipulating MongoDB database