我正在努力將 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)
我將如何解決這個問題?
uj5u.com熱心網友回復:
getDatabase().collection('htmls').find({})回傳一個FindCursor。
您需要呼叫toArray來獲取可以轉換為 JSON 的檔案陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399222.html
標籤:MongoDB
