I have MongoDB installed and I can view it through Compass. Now i want to create an Express script that will connect to MongoDB and show data on my browser. I am working through the Web Developers Bootcamp on Udemy, and so far i have this:
When I run this from PowerShell, using: node ./app.js, I get “i heard you” (from my listen function above. So I am apparently “connected” to port 27017. Now I want to see “i heard you” in the browser. I assume it should look, in browser address bar, 192.168.0.1/localhost:27017, with my “i heard you” in the browser window.
The code works fine, and try to follow it by perusing the code comments.
// app.js (or index.js)
const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => console.log('Example app listening on port ' + port))
// This line of code is for printing Hello World! in the browser,
// when you enter in the browser url bar: http://localhost:3000/
app.get('/', (req, res) => res.send('Hello World!'))
// This variable is populated in the findDocuments function (see below "Using Mongo")
var mongoDocsToDisplay = null;
// This line of code will print the collection's documents in the browser,
// when you enter in the browser url bar: http://localhost:3000/mongo
app.get('/mongo', (req, res) => res.send(
mongoDocsToDisplay
));
// Using MongoDB:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true } );
// Connect to MongoDB server, run the findDocuments function and close the connection.
client.connect(function(err) {
assert.equal(null, err);
console.log('Connected successfully to MongoDB server on port 27017');
const db = client.db(dbName);
findDocuments(db, function() {
client.close();
});
});
const findDocuments = function(db, callback) {
const collection = db.collection('test');
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log('Found the following documents:');
console.log(docs)
mongoDocsToDisplay = docs;
callback(docs);
});
}
Your Node application is actually listening to port 27017. Since 27017 is the default port used by a local MongoDB installation, typically you’d use a different port for your application (such as 3000 in @Prasad_Saya’s example).
The correct reference would be http://localhost:27017 for your original config or http://localhost:3000 for Prasad’s example. Your original URI is requesting the contents of the /localhost path from the host 192.168.0.1 on port 27017, which probably isn’t what you were expecting.
The console.log() command logs to the scripting console. To return a response to a browser/client using Express, you should call methods on Express’ response object. For example, your original script used res.send().