0

I have a nodejs project and have created a database a collection and added some data.

The url for the creation of the database is: mongodb://localhost:27017/

Code here:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

I also have angular for the view side of it.

My question is:

Can I access the data in the mongoDB created from Angular using http module as it's normally done?

Would the target url I add in angular be mongodb://localhost:27017/ ?

  • 1
    Mongo does not expose a HTTP interface all by itself: https://stackoverflow.com/questions/7386740/does-mongodb-have-a-native-rest-interface – m90 Mar 22 '19 at 10:38
  • So I have to create an api too to access the data from the browser? –  Mar 22 '19 at 10:43
  • Angular is client-side framework. MongoDB is server-side database. You need to expose public api on your server and then make queries from Angular (via HTTP). – Karol Trybulec Mar 22 '19 at 10:44
  • I'm running mongo from a nodeJs express server though. I was hoping that when I run it from node it would listen on some url –  Mar 22 '19 at 10:44

2 Answers2

0

As noted by m90, Mongo does not expose an HTTP interface natively.

You can use Node.JS rest wrapper or alternatively, you can expose in Express endpoints that your Angular app will use to fetch the data it needs.

Then in Angular create a service that uses HttpClient to make Http request to Express to fetch the data and display it.

Omri L
  • 739
  • 4
  • 12
0

All you need to do is create a REST API using expressJS and it's handler should do mongodb querying and you can initiate a HTTP request to the REST API from Angular.

Basic Express HelloWorld

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
   // You can write mongo queries here
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))
PrivateOmega
  • 2,509
  • 1
  • 17
  • 27