如何在Node.js中从MongoDB返回JSON

How to return JSON from MongoDB in Node.js?

本文关键字:MongoDB 返回 JSON 中从 js Node      更新时间:2023-09-26

我有一个名为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'));
})

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

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

在node的原生mongodb驱动程序github页面的帮助下,我能够回答我的问题:请参阅此处。

本质上,我所做的是在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());
});

当然,这个解决方案要求我对查询进行硬编码,但目前我还可以。当我走到那座桥的时候,我会跨过它。

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

result=JSON.parse(JSON.stringfy(result))

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

这可能有助于

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

您可以使用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);
     }
  });
})