mongodb nodejs - 转换循环结构

Sim*_*mon 12 javascript json mongodb node.js

我有一些代码可以从集合中提取所有文档并将其放到网页上.简化版本如下所示:

var mongodb = require("mongodb"),
    express = require("express"),
    mongoServer = new mongodb.Server('localhost', 27017),
    dbConnector = new mongodb.Db('systemMonitor', mongoServer),
    db;

var app = new express();

app.get('/drives', function(req, res) {
  db.collection('driveInfo', function(err, collection) {
    if (err) throw err;
    collection.find({}, function(err, documents) {
      res.send(documents);
    });
  });
});

dbConnector.open(function(err, opendb) {
  if (err) throw err;
  db = opendb;
  app.listen(80);
});
Run Code Online (Sandbox Code Playgroud)

我有一个driveInfo集合,其中包含一长串文档.每个文档都包含嵌套对象.我想做的是,每当有人在他们的浏览器中访问/驱动,将整个集合打印为json对象,以便我可以稍后使用jquery抓取所有内容(api的开头)

但是,我收到错误提示"TypeError:将循环结构转换为JSON".页面上的错误指向这行代码:

collection.find({}, function(err, documents) {
  res.send(documents);
});
Run Code Online (Sandbox Code Playgroud)

我不确定问题是什么,或者自我引用的位置.我不是在正确地查询收藏品吗?

Far*_*ina 17

不确定您使用的是哪个版本的API,但我认为您的语法可能在查看API规范时出错:

http://docs.mongodb.org/manual/reference/method/db.collection.find/

这是声明:

db.collection.find(<criteria>, <projection>)
Run Code Online (Sandbox Code Playgroud)

你绝对会误用投影参数.像你一样传递回调似乎返回结果中的db对象,这导致在express中的JSON序列化期间出现循环错误.

find all操作的正确代码应该类似于:

collection.find({}).toArray(function(error, documents) {
    if (err) throw error;

    res.send(documents);
});
Run Code Online (Sandbox Code Playgroud)


utk*_*h-k 6

就我而言,我收到错误是因为我正在查询(使用猫鼬查找方法)而不执行等待。请看下面

给出错误的查询(因为我没有使用await执行此查询)

const tours = Tour.find({
    startLocation: {
      $geoWithin: { $centerSphere: [[longitude, latitude], radius] }
    }
  });
Run Code Online (Sandbox Code Playgroud)

由于这个原因,我在邮递员上遇到了错误:

"message": "Converting circular structure to JSON\n    --> starting at object with constructor 'NativeTopology'\n    |     property 's' -> object with constructor 'Object'\n    |     property 'sessionPool' -> object with constructor 'ServerSessionPool'\n    --- property 'topology' closes the circle"
Run Code Online (Sandbox Code Playgroud)

我如何摆脱上述错误(添加了await):

 const tours = await Tour.find({
        startLocation: {
          $geoWithin: { $centerSphere: [[longitude, latitude], radius] }
        }
      });
Run Code Online (Sandbox Code Playgroud)