Victor
Victor

Reputation: 1205

Fail to retrieve data from MongoDb on Node.Js API

I have a MongoDb server hosted on Azure. I'm now building a Node.js API meant to retrieve data from a table on one of the databases (i.e. table: Word; database: MyDatabase). I've built the API following this tutorial, but I'm unable to successfully retrieve any data from it...

I know the server is up and running and also reachable since I can tcp-connect to it through:

psping [Azure's Public IP]:27017

Now, I have an node.js api with the following code: 1) app/server.js

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://[Azure's public IP]:27017/MyDatabase');
var Word = require('./models/word');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR API
var router = express.Router();              // get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next();
});

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

router.route('/words')

    .get(function(req, res) {
        Word.find(function(err, words) {
            if (err)
                res.send(err);

            res.json(words);
        });
    });

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

I've also written a model for my only table within the database, which has 3 columns: the auto-generated ObjectId, Spanish, French (meant to have words in both languages to make it work as a translator). The models looks like this: 2) app/models/word.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var WordSchema = new Schema({
    spanish: String,
    french: String
})

var Word = mongoose.model('Word',WordSchema);
module.exports = Word;

Now, I go to postman and GET on the following: http://localhost:8080/api/words; which returns [].

On MongoDb logs I see the following:

2016-08-05T03:16:26.520+0000 I NETWORK  [conn60] end connection [Some IP]:[Some port] (1 connections now open)
2016-08-05T03:31:11.878+0000 I NETWORK  [initandlisten] connection accepted from [Some IP]:[Some port] #61 (1 connection now open)

Upvotes: 0

Views: 174

Answers (2)

Shaun Xu
Shaun Xu

Reputation: 4676

As you mentioned in your comment that the documents were retrieved from db.word.find() I think I found the problem. You need to put documents into collection named words, instead of word.

Mongoose will use the plural version of your model name. See http://mongoosejs.com/docs/models.html for more information.

Upvotes: 1

Shrabanee
Shrabanee

Reputation: 2776

I think you are missing {} when doing find.

router.route('/words')

.get(function(req, res) {
    Word.find({}, //Added here.
      function(err, words) {
        if (err)
            res.send(err);
        console.log(words)
        res.json(words);
    });
});

Hope this will help.

EDIT:-

According the document of doc, the find function accept the first parameter as an object and treat it as conditions, but not a callback function.

Upvotes: 1

Related Questions