Home > database >  TypeError: Converting circular structure to JSON in retrieving html string from mongodb
TypeError: Converting circular structure to JSON in retrieving html string from mongodb

Time:12-31

i am working to save a html snippet into the mongodb database, the save operation is successful however retrieving the data from mongo causes a failure 'TypeError: Converting circular structure to JSON'.

the code is pretty simple

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;
  }
}

the error is

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/[email protected]@express/lib/response.js:1123:12)

How would I solve the issue?

CodePudding user response:

getDatabase().collection('htmls').find({}) returns a FindCursor.

You will need to call toArray to get an array of documents that can be converted to JSON.

  • Related