Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
});

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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

Not sure what version of the API you are using, but i think that your syntax might be wrong looking at the API spec:

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

This is the declaration:

db.collection.find(<criteria>, <projection>)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...