0

I'm trying to set up a small development environment consisting of a node.js http server, a mongodb database and frontend in angular.js. For development purposes I've created an account with MongoHQ and can reference my db using a URL.

The issue I'm faced with is that I can easily connect to my db from my Angular code but then my connection info is exposed through my http server.

So what I would like to be able to is to create my connection in my NodeJS server.js file and reference it from eg. my AngularJS app.js file. Is that possible and if so how?

Thanks in advance

1 Answer 1

1

Try using express and mongoose. Server side code

var express = require('express');
var app = express();
//start server with port of choice here
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Foo=mongoose.model('foo');
//foo is a model. Check mongoose documentation from collections and schemas

app.get('/hello', function(req, res){
   //get data from mongo using mongoose 
   foo.find({},function(err,docs){
      //do stuff here
      res.send(docs)
   })
});

Front end code

$http.get('/hello').success(function(data, status, headers, config) {
  // this callback will be called asynchronously
  // when the response is available
  //data is the data from mongodb
})

Follow this tutorial to get an idea

There is a stack called MEAN Stack. See if it fits your needs. Very easy to set up and develop.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm sorry but I still can't figure out how to reference my db connection from my AngularJS code. Or am I not supposed to do that? Am I better off just exposing functions from NodeJS that do my db operations?
You should never ever directly link your angular(front end) code to the db. You should make a call to the server(express server), the server will make a call to the db and fetch data, the server processes that data and sends it back to front end. This is how it should be done.
Will take a closer look at mongoose - thanks for the answer :-)
Sure, inform if you are stuck anywhere. Take a look at the tutorial I have given in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.