【问题标题】:How to return JSON from MongoDB in Node.js?如何在 Node.js 中从 MongoDB 返回 JSON?
【发布时间】:2016-02-01 21:30:54
【问题描述】:

我有一个名为 pokemon 的 mongodb 数据库和一个名为 pokemons 的集合。这是我尝试编写一个在 mongodb 中执行find() 操作的函数:

'use strict';

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

// db url
var url = 'mongodb://localhost:27017/pokemon';

exports.getPokemonByName = function (name) {

  MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    var cursor = db.collection('pokemons').find({name: name});

    // how to return json? 
  });

};

然后我在另一个文件中调用这个函数:

var express = require('express');
var router = express.Router();

router.get('/pokedex', function (req, res) {
  res.jsonp(db.getPokemonByName('Dratini'));
})

This link 有助于显示如何通过对游标对象执行某种each() 方法将mongodb 数据记录到控制台,但我不知道如何通过getPokemonByName 函数return json .我试图在getPokemonByName 函数的根范围内定义一个空数组,并在该链接中显示.each 方法的每次迭代时将数据推送到该数组中,但我认为我仍然无法返回该数组,因为它事后发生。

顺便说一句,我真的只是为了好玩和了解 MongoDB 和 Node.js,所以我不想使用像 Mongoose 这样的 ODM 来为我做一些工作。

【问题讨论】:

标签: javascript json node.js mongodb database


【解决方案1】:

这可能会有所帮助

var cursor =  db.collection('pokemons').find({name:name}).toArray(function(err,arr){
    return arr;
 });

【讨论】:

  • 不,您不能从异步调用中返回内联值。
  • 这在使用 mongo shell 直接查询 MongoDB 时有效。但是,正如 Blakes 提到的,从数据库获取结果的实际过程是异步的。使用最新版本的 Node 和 Mongo 库,您应该可以通过 await: let results = await db.collection('pokemons').find({ name }).toArray(); 完成此操作。
【解决方案2】:

您可以在 find 函数上使用回调来返回 json。 试试

exports.getPokemonByName = function (name,callback) {

  MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    var cursor = db.collection('pokemons').find({name: name},function(err,result){
      if(err)
      {
        callback(err,null);
      }

      if(result)
        callback(null,result);
    });

  });

};

router.get('/pokedex', function (req, res) {
  db.getPokemonByName('Dratini',function(err,result){
     if(result)
     {
        res.jsonp(result);
     }
  });

})

【讨论】:

  • getPokemonByName(name) 函数仍然没有返回任何内容。
  • 检查编辑。现在使用回调返回 json。
  • 似乎应该可以工作,但会产生循环引用错误:TypeError: Converting circular structure to JSON。说不出为什么。
【解决方案3】:

在 node 的本地 monogodb 驱动程序 github 页面的帮助下,我能够回答我的问题:See here.

本质上,我所做的是在 MongoClient 的连接函数中定义我的导出函数。出于某种原因,我认为节点导出必须位于模块的根目录中,但事实并非如此。这是一个完成的版本:

'use strict';

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

// db url
var url = 'mongodb://localhost:27017/pokemon';

var findDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('pokemons');
  // Find some documents
  collection.find({name: 'Dratini'}).toArray(function(err, docs) {
    assert.equal(err, null);
    // assert.equal(2, docs.length);
    console.log("Found the following records");
    callback(docs);
  });
}

// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");
  findDocuments(db, function(docs) {
    console.log(docs);
    exports.getPokemonByName = function() {
      return docs;
    }
    db.close();
  });
});

然后在另一个文件中:

var express = require('express');
var router = express.Router();

router.get('/pokedex', function (req, res) {
  res.jsonp(db.getPokemonByName());
});

当然,这个解决方案需要我对查询进行硬编码,但我现在可以接受。当我到达时会穿过那座桥。

【讨论】:

    【解决方案4】:

    为此找到了一个简单的调整。假设 findOne 的回调返回结果,那么您可以像这样将结果转换为 JSON 对象

    结果 = JSON.parse(JSON.stringify(result))

    现在您只需使用点运算符即可访问结果及其字段。

    【讨论】:

    • 太棒了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多