Last lesson learned how to use node. js to connect to a database, and this lesson we learned how to insert data.
1, using node. js to connect MongoDB data successfully, want to write data in the database, but show that db.collection is not a function. The Test.js code is as follows:
varExpress = Require ("Express");varApp =Express ();varMongoclient = require (' MongoDB '). mongoclient;varassert = require (' assert ');//for debugging information//Connection URLvarurl = ' Mongodb://localhost:27017/stu ';//connection address, slash "/myproject" means database, automatically created if not presentApp.get ("/",function(req,res) {mongoclient.connect (URL,function(Err, DB) {//Use Connect method to connect to the server //The callback function indicates 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; } console.log ("Connected successfully to server"); Insertdocuments (DB,function(Result) {Console.log (result);}); }); Res.send ("Hello.");}); App.listen (3000);varInsertdocuments =function(DB, callback) {//Get the MyTestDatabase collectionDb.collection (' MyTestDatabase '). Insertone ([{"Hahaha": 1} ], function(err, result) {Console.log ("Inserted 3 documents into the collection"); Callback (result); Db.close (); });}
Run command in CMD: node test.js, console error is as follows:
2, the solution (see: https://segmentfault.com/q/1010000012306610)
This error is out of the MongoDB library, only need to node_modules in the MongoDB version of the 2.3.33vision can be resolved;
"Dependencies": {"^2.2.33"}
And then:
NPM Install
3. Run node Test.js again
02_ inserting data into MongoDB using node. js