Zaisty
Zaisty

Reputation: 29

Cannot read property 'insertOne' of undefined, MongoDB

I wanted to write my first application with the help of node.js and MongoDB. Unfortunately I don't know what I'm doing wrong. Thanks for all the tips.

const prompt = require('prompt-sync')();
const mongo = require('mongodb');
const client = new mongo.MongoClient('mongodb://localhost:27017', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

var db;
var animals;
client.connect(() => {
  db = client.db('test');
  animals = db.collection('animals');
});


addAnimal = () => {
  const animalName = prompt('Name: ');
  const ageAnimal = prompt('Age: ');
  animals.insertOne(
    {
      nameAnimal: animalName,
      age: ageAnimal,
    },
    (err) => {
      if (err) {
        console.log('Error');
      } else {
        console.log('Added!');
      }
    }
  );
};
addAnimal()

Upvotes: 1

Views: 5286

Answers (1)

JME
JME

Reputation: 503

The problem is that addAnimal() call is executed before the connection is established. The callback passed to client.connect is async - it will execute "later". By the time you call addAnimal the callback wasn't executed (yet) and therefore animals is still undefined.

A solution would be to place addAnimal into the client.connect callback like so:

client.connect(() => {
  db = client.db('test');
  animals = db.collection('animals');
  addAnimal();
});

Upvotes: 3

Related Questions