How To Get Data From MongoDB To AngularJS Using Express And Nodejs

71 views
Skip to first unread message

EverydayDiesel

unread,
Aug 4, 2014, 5:22:16 PM8/4/14
to ang...@googlegroups.com
Hello

I am trying to get a MEAN application up and going.  I have learned (barely) each individual piece and now it is time to code.


I must be missing something and I think it is the client / server javascript that is throwing me off.

This is what I have

express MeanTest --ejs

cd MeanTest && npm install

npm install mongodb --save

then I add the following code to the files below.

app.js (under the other 'requires')
var mongoDbInstance = require('mongodb').MongoClient;


index.ejs
<!DOCTYPE html>
<html ng-app="phonecatApp">
 
<head>
   
<title><%= title %></title>
   
<link rel='stylesheet' href='/stylesheets/style.css' />
     
<script src="/javascripts/angular.min.js" ></script>
     
<script src="/javascripts/countriesCtrl.js"></script>

 
</head>
 
<body>
   
<h1><%= title %></h1>
   
<p>Welcome to <%= title %></p>

       
<div>
       
<label>Name:</label>
       
<input type="text" ng-model="yourName" placeholder="Enter a name here">
               
<hr>
               
<h1>Hello {{yourName}}!</h1>
       
</div>


       
<div ng-controller="PhoneListCtrl">
           
<table border="1" cellspacing="0"  cellpadding=3>
               
<tr><td>Abbreviation</td><td>Name</td></tr>
               
<tr ng-repeat="state in states">
                   
<td>{{state.abbreviation}}</td><td>{{state.name}}</td>

               
</tr>
           
</table>

       
</div>
 
</body>
</html>


countriesCtrl.js
var phonecatApp = angular.module('phonecatApp', []);

phonecatApp
.controller('PhoneListCtrl', function ($scope) {

   
var db = mongoDbInstance.connect('mongodb://127.0.0.1:27017/website', function(err, db) {
       
if(err) {
            console
.log("error");
           
throw err;
       
}
       
else
       
{
            console
.log("no error");
       
}
        console
.log("connected to the mongoDB !");
        myCollection
= db.collection('test_collection');
   
});

    $scope
.states = myCollection;

   
});



The error I get is below, probably because it the instance is declared in the server and the client doesnt know about it.
So my question is, how can I get the data to the client?

Error: mongoDbInstance is not defined


I have read example after example and none of them so far address this question.  Thanks in advance.





Reply all
Reply to author
Forward
0 new messages