无法读取未定义的MongoDB属性“ insertOne”

我想在node.js和MongoDB的帮助下编写我的第一个应用程序。不幸的是,我不知道我在做什么错。感谢所有的提示。

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()
评论
夜~太美
夜~太美

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();
});
点赞
评论