0

I am not able to insert data into MongoDB database using insert method in Nodejs.

var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
  if (err) throw err;
  // db gives access to the database
  const myDb = db.db('learnyoumongo');
  var docs = myDb.collection('docs');
  var obj = {firstName: process.argv[2], lastName: process.argv[3]};
  docs.insert(obj, function(err, res){
    if(err) throw err;
    console.log('data inserted');
  })
  db.close();
}

There is no output coming and connection to the data base is successful but no insertion of data is happening.

3 Answers 3

2

Try this will work for you .

var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, dbobj) {
  if (err) throw err;
  // db gives access to the database
 // const myDb = dbobj.db('learnyoumongo').collection('docs');
 // var docs = myDb.collection('docs');
  var obj = {firstName: process.argv[2], lastName: process.argv[3]};
  dbobj.db('learnyoumongo').collection('docs').insert(obj, function(err, res){
    if(err) throw err;
    console.log('data inserted');
    dbobj.close();
  })

})
Sign up to request clarification or add additional context in comments.

Comments

0

I figured out what the problem is. Seems like I forgot to add a parenthesis in the end:

var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
  if (err) throw err;
  // db gives access to the database
  const myDb = db.db('learnyoumongo');
  var docs = myDb.collection('docs');
  var obj = {firstName: process.argv[2], lastName: process.argv[3]};
  docs.insert(obj, function(err, res){
    if(err) throw err;
    console.log('data inserted');
  })
  db.close();
})

Comments

0

You can use the following code to insert data into MongoDB using nodejs.

var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/learnyoumongo";

mongo.connect(url, function(err, db) {
if (err) throw err;
//access to the database
var myobj = { firstname: "Jhon", lastname: "Mackey" };
db.collection("docs").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("Data inserted");
db.close();
 });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.