02_ inserting data into MongoDB using node. js

Source: Internet
Author: User
Tags mongoclient mongodb version

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

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.