user2677095 user2677095 - 3 years ago 186
Node.js Question

Node.js REST API to fetch data from MongoDB

I'm trying to create a REST API using Node.js that would fetch the last N rows of a MongoDB collection. This is my current code:

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongodb = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
var db;

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

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/sample", function(err, database) {
if(err) return console.error(err);

db = database;

// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});

// Reuse database object in request handlers
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
}).limit(10,function(e,d){});
});

app.use('/',router);

app.listen(3000);
console.log("Listening to PORT 3000");


This is successfully printing out all of the contents of the database on the server console (Whenever the client makes a get request). However, how do I give this JSON information to the client making the GET call instead in an efficient way (and one that supports the situation where the client can add a parameter N that would only fetch the last N rows of the database). I looked into Mongoose and that seemed pretty solid but in my case I already have a pre-existing database and collection so wasn't sure if that was the best route for this task.

If you need any more info or clarification, feel free to let me know! Thanks for reading!

Answer Source

Instead of res.end, you would use res.send and send the response back to the front end.

router.get("/", function(req, res, next) {
  db.collection("samplecollection").find({}, function(err, docs) {
    if(err) return next(err);
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
        var response = {
              statusCode: 200,
              headers:  { 'Content-Type': 'application/json' },
              body:    JSON.parse(doc)
            }
        res.send(response);
      }
    });
  });
});

To get the last N records of a collection, you could use a combination of sort and limit. First, sort on a specific field such as date in ascending/descending order and then limit the results to whatever N is. Something like this:

db.collection.find({ query }).sort({ key: 1 }).limit(N)

UPDATE:

Based on our ongoing comment conversation, here is an example of how I have successfully sent data back to the client. This does not include the limit or anything fancy.

var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var db = require('./config/db');
var bodyParser = require('body-parser');


app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

app.get('/', function(req, res) {

  db.find({}, function(err, data) {
    if (err) {
      console.log(err);
      return res.send(500, 'Something Went wrong with Retrieving data');
    } else {
      // console.log(data[0]);
      res.json(data);
    }
  });

});

app.listen(port);
console.log('Server listening on port: ', port);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download