I’m working on the URL Shortener API, I store the data in the database and when i try to retrieve it with a get route, this happens:
this is the code
app.route('/:short_url_index')
.get(function (req, res) {
MongoClient.connect(Mongo_URI, function (err, db) {
if (err) return console.log('Error connecting to the Database', err);
var short_url_index = parseInt(req.params.short_url_index);
db.collection('urls').findOne({
short_url_index: short_url_index
}, function (err, doc) {
res.redirect(doc.original_url);
});
db.close();
});
});
i’m basically trying to query the database by the short url and get the original url, but i get this error in the cmd:
Node.js listening ...
*
*
C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb\lib\utils.js:123
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property 'original_url' of null
at C:\Users\hamza\Desktop\url_shortener\server.js:100:25
at handleCallback (C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb\lib\utils.js:120:56)
at C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb\lib\collection.js:1417:5
at handleCallback (C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb\lib\utils.js:120:56)
at C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb\lib\cursor.js:682:5
at handleCallback (C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb-core\lib\cursor.js:171:5)
at setCursorNotified (C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb-core\lib\cursor.js:515:3)
at C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb-core\lib\cursor.js:590:16
at queryCallback (C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb-core\lib\cursor.js:232:18)
at C:\Users\hamza\Desktop\url_shortener\node_modules\mongodb-core\lib\connection\pool.js:469:18
[nodemon] app crashed - waiting for file changes before starting...
but when i try to log the document retrieved from the database, i get it correctly and it’s not undefined