Sebastian Avila
Sebastian Avila

Reputation: 55

Node.js get request from MongoDB returning undefined

I'm trying to build a small web app as I try to learn MEAN stack web development.

I have a running MongoDB with a collection named 'contactlist', this list will then be accessed by a Node.js/Express.js server to retrieve the information into a JSON object and pass it through an angular controller.

var express = require('express');
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var app = express();
const port = 80;

app.use(express.static(__dirname + "/public"));
app.get('/contactlist', function(req, res){
    console.log("I received a GET request")
    db.contactlist.find(function(err, docs){
        console.log("Getting data from db");
        console.log(docs);
        res.json(docs);
    });
    console.log("Returned data");
});

app.listen(port,'0.0.0.0');
console.log('Server running on port '+port);

Included code for controller

var myApp = angular.module('myApp',[]);

myApp.controller('AppCtrl',['$scope','$http',function ($scope,$http){
    console.log("Hello World")
    console.log("Getting data from server")
    $http.get('/contactList').success(function(response){
        console.log("I got the data I requested");
        $scope.contactList = response;
    })
}]);

log from the server:

C:\Users\savila\Documents\Code\contactListApp>node server
Server running on port 80
I received a GET request
Returned data
Getting data from db
undefined

Upvotes: 2

Views: 3356

Answers (3)

Hayden Braxton
Hayden Braxton

Reputation: 1161

It seems all of the previous posters have incorrectly assumed that you are using the standard mongodb driver package for node, which you are not. According to the mongojs documentation, calling find with only a callback is valid. It will give you an array of all documents in the collection and you do NOT need to pass in an empty object, as has been previously suggested.

Honestly, reading through the mongojs documentation, I would advise against using the package, as explained in my comment to your question. Their documentation is a little confusing in some places, and really they are just reinventing the wheel, as the mongodb package already give the functionality you need, and more.

One thing you're missing though, is you need to check for erros in your find callback. Below is how I would refactor the code. This may not solve your problem, but it will at least log to your console what error you're getting, which is probably what's happening.

app.get('/contactlist', function(req, res){
    console.log("I received a GET request");

    db.collection('contactlist').find(function(err, docs){
        console.log("Getting data from db");

        /*  You need to check for errors here.
            If there is an error in retreiving your data, docs will be undefined
        */

        if (err) {
          console.log('error from mongodb', err);
          res.send('error retrieving data')
          // or however else you want to handle your error
        } else {
          console.log('docs from mongodb', docs);
          res.json(docs);
          console.log("Returned data");
        }
    });

});

Also, in your angular code, you probably want to say $scope.contactList = response.data;. According to $http docs, the data field of the response object is going to carry the data returned from the server, while the response object itself contains additional information, like status, headers, and so on.

Hope this helps. Please comment if you have any questions or need clarification. Best of luck learning the MEAN stack.

Also, for your benefit, here are the mongojs docs and the mongodb docs, and again, I would advise using the latter.

Upvotes: 0

abdulbari
abdulbari

Reputation: 6232

You are not passing the query object

Pass empty query object {} to get all items

Syntax of find query

db.collection.find(query, projection)

Check doc for find query find()

app.get('/contactlist', function(req, res){
    console.log("I received a GET request")
    db.contactlist.find({},function(err, docs){
        console.log("Getting data from db");
        console.log(docs);
        res.json(docs);
    });
    console.log("Returned data");
});

Upvotes: 1

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

It may be that your connection with mongo database is not establish or other several possible issues but main issue is that not passing query object

Pass empty query object {} to get all items or for selecting specific record passing like this {'key':data'}

db.contactlist.findOne({},function(err, docs){
        console.log("Getting data from db");
        console.log(docs);
        res.json(docs);
    });

Upvotes: 0

Related Questions