Reputation: 529
I'm on my local Ubunto machine and following a tutorial to learn node/mongodb. 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('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}
console.log('data inserted');
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
My driver version: "mongodb": "^2.2.5"
My mongodb version v3.2.20
I can see Connected to MongoDB server
is being printed out but I don't get the result json in the terminal, nor the data inserted
alert. What is wrong here? How can I fix it?
Upvotes: 0
Views: 72
Reputation: 5944
I think you close connection too early, try to move close()
into insertOne
callback:
console.log('data inserted');
console.log(JSON.stringify(result.ops, undefined, 2));
db.close();
Upvotes: 2