TypeError:更改为NodeJS Async Await时将循环结构转换为JSON

时间:2017-07-29 17:06:08

标签: node.js mongodb async-await

我最近了解了NodeJS Async / Await。更改了我的代码,使其更清晰,更易于阅读。

  • 升级到NodeJS 8.2.1。
  • MongoDB 2.2.30
  • Express 4.1.4

代码如下所示:

    var express = require('express');
    var router = express.Router();
    var MongoClient = require('mongodb').MongoClient;
    var assert = require('assert');
    var url = process.env.mongo;


    /* GET home page. */
    router.get('/', async function(req, res, next) {
      try{
        let db = await MongoClient.connect(url);
        let col = await db.collection('product');
        let documents = await col.find();
        return res.send(documents)
      }catch(err){
        console.log(err)
      }

    });


module.exports = router;

遇到此错误的问题,

TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at stringify (/home/edmondtm/test-async/node_modules/express/lib/response.js:1064:12)
at ServerResponse.json (/home/edmondtm/test-async/node_modules/express/lib/response.js:243:14)
at ServerResponse.send (/home/edmondtm/test-async/node_modules/express/lib/response.js:152:21)
at /home/edmondtm/test-async/routes/index.js:15:16
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

注意:如果更改没问题: let documents = await col.find();至 let documents = await col.findOne();

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

尝试 let documents = await col.find().toArray()

col.find()someCursor.toArray()返回承诺时返回游标。