How to retrieve mongodb data from server (node.js) to my AngularJS Route

This is my Server.js file (NodeJS):

var express = require('express');
var server= require('http');
var path= require("path");
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var app= express();

var staticDIR = path.resolve(__dirname, "./www");``
app.use(express.static(staticDIR));
app.use(bodyParser.json());
app.get("*", function (req, res) {
    var indexViewPath = path.resolve(__dirname, "./www/index.html");
    res.sendFile(indexViewPath);
});
var dbURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose disconnected');
});
process.on('SIGINT', function() {
    mongoose.connection.close(function () {
        console.log('Mongoose disconnected through app termination');
        process.exit(0);
    });
});

var userSchema = new mongoose.Schema({
    name: String,
    password:String,
    email: {type: String, unique:true},
    createdOn: { type: Date, default: Date.now }
    //modifiedOn: Date,
    //lastLogin: Date
});

mongoose.model( 'User', userSchema );
var User = mongoose.model('User');

var CompanySchema = new mongoose.Schema({
    CompanyName: String,
    password:String,
    email: {type: String, unique:true},
    createdOn: { type: Date, default: Date.now }
    //modifiedOn: Date,
    //lastLogin: Date
});
mongoose.model( 'company', userSchema );
var company = mongoose.model('company');

User.find({}, function(err, users) {
    if(!err){
        console.log(users);
    }
});

company.find({}, function(err, users) {
    if(!err){
        console.log(users);
    }
});

app.post('/account', function(req, res){
    new company({
        CompanyName:req.body.Company,
        email:req.body.email,
        password:req.body.password
    }).save(function(err,doc){
            if(err)res.json(err);
            else res.send("succesfully inserted");
            console.log(res);

        });
});

This is my Middleware to get tha data:

app.get('/details', function (req, res) {
    console.log('I received a GET request');
    company.find({}, function(err, users) {
        if(!err){
            console.log(users);
        }
        else{
            res.render('/details',{users:docs})
        }
    });

});


app.listen(9000);
console.log("Server Running on port 3000");

This is my Controller.js (AngularJS) file:

   angular.module('myApp', ['ngMaterial','firebase','ui.router'])
        .controller('detailsCtrl', function($scope,myfirebaseAddress,$location,$timeout) {
            var ref = new Firebase(myfirebaseAddress);

        })

This is my route where I want to show the mongoDb saved data

 <ui-view>
        <div class="sub-header">
            <h3>Company Details</h3>
        </div>

    <ul>
       <li ng-repeat="users in user">
           {{user.email}}
       </li>
    </ul>
    </ui-view>

Thanks in advance

Upvotes: 1

Views: 11383

Answers (4)

Controller to get the requested data

.controller('detailsCtrl', function($scope,$http) {

    $scope.users = [];

    $http.get('/details').then(function(d)
        {
            console.log(d);
            $scope.users= d.data;
        },function(err)
        {
            console.log(err);            }
    )

})

server route

app.get('/details', function (req, res) {
    console.log('I received a GET request');
    company.find({}, function(err, users) {
        if(!err){
           res.json(users);
        }

    });

});

Upvotes: 1

jlex
jlex

Reputation: 1

Try to use the angular http module to get the node/express response that get the data from mongodb in client side; like this: https://github.com/J-Alex/api_rest_mvc

Upvotes: 0

mammuthone
mammuthone

Reputation: 59

If you want to retrieve your data, you must stop this:

res.render('/details',{users:docs})

If you want to serve data with an angular app, you have to stop to render a view and start to give back a json in your response.

res.jsonp(users)

Then you've to adjust your controller. Write a service like:

angular.module('yourApp')
.service('userService', function($http){
    return {
        getUsers: function(url) {
            return $http.get(url)
            }
        }
    })

this should return an http promise. In your controller you handle this promise this way:

$scope.users = function(){
        userService.getUsers('/users')
            .then(function(users){
                //You have your users object
            })
    }

remember to handle the unsuccesfull case of your promise

Upvotes: 0

satya
satya

Reputation: 3560

instead if writing below code

if(!err){
        console.log(users);
    }
    else{
        res.render('/details',{users:docs})
    }

do like this

if(!err){
            res.send(users);
        }
        else{
            res.send('could not retrived data');
        }

in controller side you can get your all data inside success call back function.here also check

app.listen(9000);
console.log("Server Running on port 3000");

this should like below.

app.listen(9000);
console.log("Server Running on port 9000");

Upvotes: 2

Related Questions