mongodb nodejs -转换循环结构

k75qkfdt  于 5个月前  发布在  Node.js
关注(0)|答案(5)|浏览(50)

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

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的开始)
然而,我得到一个错误,说“TypeError:Converting circular structure to JSON”。页面上的错误指向这行代码:

collection.find({}, function(err, documents) {
  res.send(documents);
});


我不确定是什么问题,或者自我引用在哪里。我没有正确查询集合吗?

mznpcxlj

mznpcxlj1#

不确定您使用的是哪个版本的API,但我认为您的语法可能是错误的,请查看API规范:
http://docs.mongodb.org/manual/reference/method/db.collection.find/
这是一个声明:

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

字符串
而且你肯定是误用了projection参数。像你这样传递一个回调似乎会在结果中返回db对象,这会导致express中JSON序列化过程中的循环错误。
查找所有操作的正确代码应该类似于:

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

    res.send(documents);
});

lrl1mhuk

lrl1mhuk2#

在我的例子中,我得到了错误,因为我正在查询(使用 Mongoose 查找方法),而没有执行等待。

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

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

字符串
错误,我得到了 Postman 由于这一点:

"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"

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

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

r6hnlfcb

r6hnlfcb3#

回调选项来自Mongoose而不是MongoDB,参见文档。

// Mongoose Docs : callback option
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// Example
app.get( '/api/users' , (req,res,done)=>{
  let getUsers = NewUser.find({},(err,data)=>{
    if(err) return done(err);
    res.json(data)
  });
});

字符串
注意,响应进入回调,在您的情况下,

YourModel.find({}, function(err, documents) {
  if(err) return done(err);
  res.send(documents);  //  <-- here
});
// <-- not here


在Mongo中,有一个 *cursor方法 * 来访问文档next(),参见docs:

var myCursor = db.bios.find( );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;
if (myDocument) {
    var myName = myDocument.name;
    print (tojson(myName));
}


你可以在manual/crud找到mongo文档中的CRUD操作。在Query Documents中你会看到db.inventory.find( {} ):要选择集合中的所有文档,将一个空文档作为查询过滤器参数传递给find方法。
异步/等待功能解决方案:Mongo Docs

app.get( '/api/users' , async (req,res)=>{
  const getUsers = await NewUser.find({});
  res.json( getUsers );
})


< callback >解决方案: Mongoose 鱼。

app.get( '/api/users' , (req,res,done)=>{
  let getUsers = NewUser.find({},(err,data)=>{
    if(err) return done(err);
    res.json(data)
  });
});

eoigrqb6

eoigrqb64#

第一个月
这里,res1将包含一个具有循环结构的“cursor”,因此抛出给定的错误。
尝试将const res2 = await res1.toArray()添加到代码中。
在这里,res2现在将包含一个文档数组,由光标res1指向,这是您正在查询的文档。

8fsztsew

8fsztsew5#

在我的例子中,我忘记了等待.find()方法,并在响应中发送了一个未解决的promise。
改变了这个:

const posts = Post.find({});

字符串
对此:

const posts = await Post.find({});

相关问题