2

I have been trying to work with mongodb and to insert some data but I am getting an error . Here is the code .

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
  if (err) {
    return console.log('Unable to connect to MongoDB server');
  }
  console.log('Connected to MongoDB server');


  db.collection('Users').insertOne({
    name: 'Andrew',
    age: 25,
    location: 'Philadelphia'
  }, (err, result) => {
    if (err) {
      return console.log('Unable to insert user', err);
    }

    console.log(result.ops);
  });

  db.close();
});

1 Answer 1

6

The native driver for MongoDB has changed what its .connect() method provides to you in recent versions.

3.0

connectCallback(error, client)

2.2

connectCallback(error, db)

These being how your (err, db) => { ... } callback is defined in the documentation.


The .connect() method provides you a MongoClient instance. Including the database name in the connection address at least doesn't appear to change that.

You'll have to instead use the client's .db() method to get a Db instance with collections.

const dbName = 'TodoApp';

MongoClient.connect('mongodb://localhost:27017/', (err, client) => {
  if (err) { ... }

  let db = client.db(dbName);

  db.collection('Users')...;
});
Sign up to request clarification or add additional context in comments.

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.