0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.