Harry
Harry

Reputation: 109

Passing data from mongodb to my front end application

I have a MongoDB on a web server and I have a Mean stack web application. Within the MongoDB, I have a bunch of data that I want to pass to my web application. I have looked into options, but I'm a little unsure as to which route to take to make this happen. I have considered using socket.io to set up a listener on my web server to open up a connection with my DB, and then making an API call or direct DB connection to return my data.

I should add that my app is based on the mean.io boilerplate code.

My question is where within my stack do I need to put the socket.io code?

Would it be wise to include the socket.io code at the root of my application or only in the packages/modules that require the data to be passed from my web server to my application?

And finally, is socket.io even the preferred route to take? Is there another method to achieve this that makes more sense such as express.js?

Upvotes: 1

Views: 2036

Answers (2)

frozen
frozen

Reputation: 2154

There's no need to use socket.io unless you want real-time constant, persistant streaming of information from your database to your front-end.

First in your express app, connect to the db with https://github.com/mongodb/node-mongodb-native. Then, you can just set up a JSON endpoint route for the data to get sent to. Then the client webpage that needs the data simply sends an XHR request to the JSON page.

EDIT: OP does want to use socket.io.

If you want to use socket.io, you have to include it on both the server and the client.

Server-side:

const express = require('express');
const app = express();
const server = require('http').Server(app);
// socket.io
const io = require('socket.io').listen(server);
// handling socket.io requests
io.on('connection', (socket) => {
  log.info('new connection.');
  socket.emit('data', {/** whatever data you need to send **/});
  socket.on('disconnect', (e) => {
    log.info('user disconnected.');
  });
});

Client-side:

Be sure to include socket.io in the html file (get it from the website). Then, in your client-side js:

const socket = io();
socket.on('connect', () => {
  console.log('connected to server.');
});
socket.on('disconnect', () => {
  console.log('disconnected.');
});
socket.on('data', (data) => {
    // this is where you receive the data
    // do something with your data
});

Upvotes: 1

Macgyver Martins
Macgyver Martins

Reputation: 96

You should create a route in Express and then, request that route from your angular SPA with an http module, like $http ou Restangular. Take a look at this article https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application

Upvotes: 1

Related Questions