问题描述
我有一些代码可以从集合中提取所有文档并将其放到网页上。简化版本如下所示:
I have some code that pulls all documents from a collection and puts it onto a webpage. a simplified version looks like this:
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);
});
我有一个包含很长文档列表的driveInfo集合。每个文档都包含嵌套对象。我想做的是,每当有人在他们的浏览器中访问/驱动时,将整个集合打印为json对象,以便我可以稍后使用jquery抓取所有内容(api的开头)
I have a driveInfo collection which contains a long list of documents. Each document contains nested objects. What I would like to do, is whenever someone visits /drives in their browser, to print the entire collection as a json object so that I can grab everything with jquery later (beginnings of an api)
但是,我收到错误提示TypeError:将循环结构转换为JSON。页面上的错误指向这行代码:
However, I get an error saying "TypeError: Converting circular structure to JSON". The error on the page points to this line of code:
collection.find({}, function(err, documents) {
res.send(documents);
});
我不确定问题是什么,或者自我引用的位置。我没有正确查询集合吗?
I'm unsure what the problem is, or where the self-reference is. Am I not querying the collection properly?
推荐答案
不确定您使用的是哪个版本的API,但我认为您的语法查看API规范可能有误:
Not sure what version of the API you are using, but i think that your syntax might be wrong looking at the API spec:
这是声明:
db.collection.find(<criteria>, <projection>)
你肯定在滥用投影参数。像你一样传递回调似乎返回结果中的 db 对象,这导致在快递中JSON序列化期间出现循环错误。
And you are definitely misusing the projection parameter. Passing a callback like you are doing seems to return the db object in the result, which is causing the circular error during JSON serialization in express.
查找所有操作的正确代码应该类似于:
The correct code for the find all operation should be something like:
collection.find({}).toArray(function(error, documents) {
if (err) throw error;
res.send(documents);
});
这篇关于mongodb nodejs - 转换循环结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!