我最近了解了NodeJS Async / Await。更改了我的代码,使其更清晰,更易于阅读。
代码如下所示:
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();
希望有人可以帮助我。
答案 0 :(得分:0)
尝试
let documents = await col.find().toArray()
col.find()
在someCursor.toArray()
返回承诺时返回游标。