我想在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 toclient.connect
is async - it will execute "later". By the time you calladdAnimal
the callback wasn't executed (yet) and thereforeanimals
is still undefined.A solution would be to place
addAnimal
into theclient.connect
callback like so: