简体   繁体   中英

db.collection is not a function on using mongodb

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();
});

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')...;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM