我正在将一个html片段保存到mongodb数据库中,保存操作成功,但从mongo检索数据会导致"TypeError:将循环结构转换为JSON"失败。
代码很简单
let database;
let connection;
exports.connectDatabase = function(MONGO_URL,DB_NAME) {
MongoClient.connect( MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
database = client.db(DB_NAME);
connection = client;
}
);
};
exports.getDatabase = function(){
return database;
};
exports.saveHtml = async function(req, res) {
try{
await getDatabase().collection('htmls').insertOne({name:req.body.title, html:req.body.content });
res.send('success');
}catch(e){
console.log(e);
res.json(404);
return;
}
}
exports.getSavedHtmls = async function(req,res){
try{
let html = await getDatabase().collection('htmls').find({});
res.send(html);
}catch(e){
console.log(e);
res.json(404);
return;
}
}
错误是
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'NativeTopology'
| property 's' -> object with constructor 'Object'
| property 'sessionPool' -> object with constructor 'ServerSessionPool'
--- property 'topology' closes the circle
at JSON.stringify (<anonymous>)
at stringify (/Users/xisizhe/Documents/server/node_modules/_express@4.17.1@express/lib/response.js:1123:12)
我该如何解决这个问题?
getDatabase().collection('htmls').find({})
返回一个FindCursor。
您需要调用toArray来获得一个可以转换为JSON的文档数组。