I am tying out node.js, but not able to wrap my head around why one works and other doesn’t
can you explain to me why
this works:
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('note')
.deleteOne(details)
.then((result) => res.send(result))
.catch((err) => {
!error.logged && logger.error('Mongo error', err);
error.logged = true;
throw err;
});
});
but this never enters the callback function and gets stuck in deleteOne, but in db we see entry is removed
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('note').deleteOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
also all examples i see , they say below code should work but it never enters callback, it does make db connection i can see in db logs
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
console.log("hello");
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
console.log("bye");
what exactly i am missing here, or there is issue with my system?
this below a very simple example of callback from chatgpt works
const fs = require('fs');
// Function to read a file asynchronously and invoke a callback when done
function readFileAsync(filePath, callback) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
callback(err, null); // Pass the error to the callback
} else {
callback(null, data); // Pass the data to the callback
}
});
}
// Example usage of the readFileAsync function
const filePath = 'example.txt';
readFileAsync(filePath, (err, data) => {
if (err) {
console.error('Error reading the file:', err);
} else {
console.log('File content:', data);
}
});
why inbuilt callbacks not working?
3
Answers
my "mongodb": "^6.0.0" and mongodb has removed callback from 5.0.0 from this doc mongo release doc ,concluding this is the reason why callbacks to db is not working. If anyone has other reasons please share
This is the expected behaviour in the versions 5.x+ of the MongoDB API.
See MongoDB docs: Upgrade Driver Versions:
This change had been announced at the release of version 4.10:
This has nothing to do with Node.js and everything to do with the MongoDB driver.
See the documentation.
The examples that you say you see, which show the callback approach working, are old and out of date. When a third-party tutorial doesn’t work, you should check against the official documentation.