最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js REST API to fetch data from MongoDB - Stack Overflow

programmeradmin1浏览0评论

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 remends 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!

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 remends 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!

Share Improve this question edited Sep 29, 2017 at 18:27 user2677095 asked Sep 29, 2017 at 18:09 user2677095user2677095 4712 gold badges9 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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 bination 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 ment 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);

Ended up fixing my issue. Changed my get statement to this:

router.get("/", function(req, res, next) {

db.collection("samplecollection", function(err, collection){
    collection.find({}).limit(10).toArray(function(err, data){
            res.json(data);
  })
});
});
发布评论

评论列表(0)

  1. 暂无评论