简体   繁体   English

Node.js REST API用于从MongoDB获取数据

[英]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. 我正在尝试使用Node.js创建一个REST API,它将获取MongoDB集合的最后N行。 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). 这样就可以在服务器控制台上成功打印出数据库的所有内容(每当客户端发出get请求时)。 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). 但是,如何以有效的方式将此JSON信息提供给进行GET调用的客户端(并且支持客户端可以添加仅获取数据库的最后N行的参数N的情况)。 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. 我查看了Mongoose,看起来非常可靠,但在我的情况下,我已经有一个预先存在的数据库和集合,因此不确定这是否是此任务的最佳途径。

If you need any more info or clarification, feel free to let me know! 如果您需要更多信息或说明,请随时告诉我们! Thanks for reading! 谢谢阅读!

Instead of res.end , you would use res.send and send the response back to the front end. 您将使用res.send而不是res.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 . 要获取集合的最后N条记录,可以使用sortlimit的组合。 First, sort on a specific field such as date in ascending/descending order and then limit the results to whatever N is. 首先,按照升序/降序对特定字段(如日期)进行排序,然后将结果限制为N。 Something like this: 像这样的东西:

db.collection.find({ query }).sort({ key: 1 }).limit(N) 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);

Ended up fixing my issue. 结束我的问题。 Changed my get statement to this: 将我的get语句更改为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM