K
K
krax13372020-05-05 13:47:54
JavaScript
krax1337, 2020-05-05 13:47:54

How to fix the Converting circular structure to JSON error when displaying all elements of a collection from MongoDB, as well as individual fields through mongoose?

I want to return it is simple to return certain objects from the collection, but this does not work. Did everything as in the example.

Error code:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ReplSet'
    |     property 's' -> object with constructor 'Object'
    |     property 'coreTopology' -> object with constructor 'ReplSet'
    |     ...
    |     property 's' -> object with constructor 'Object'
    --- property 'topology' closes the circle


My GET method:

router.get('/assignments', auth.required, function (req, res, next) {
  var user = User.findById(req.payload.id);

  if (!user) { return res.sendStatus(401); }

  var assignments = Assignment.find({ author: user });

  return res.json({
    assignments: assignments.map(function (assignment) {
      return assignment.toJSONFor(user);
    })
  })
})


JSON generation method in Mongoose model

AssignmentSchema.methods.toJSONFor = function(user){
  return {
    slug: this.slug,
    publicSlug: this.publicSlug,
    title: this.title,
    description: this.description,
    createdAt: this.createdAt,
    updatedAt: this.updatedAt,
    attempts: this.attempts,
    questions: this.questions,
    author: this.author.toProfileJSONFor(user)
  }
};


Do you have any ideas how to simplify this or get rid of the error?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question