Converting circular structure to JSON, can't see anything circular

dev-mirzabicer

I'm learning back-end web development and the course I'm following includes making a REST API for a system that has "tours". I use MongoDB and Mongoose and everything was fine, I was filtering the query according to the parameters and that went well. But then the instructor wanted to put this filtering process (and other query processes) into a class and access them inside this class. After I've done this, I started getting this error. So I know that you can't convert a circular object to JSON, nor can you stringify such an object. But I don't have any... circular objects. Or at least I don't think so. I'm just a beginner, so forgive my mistakes if you will. Here's the code:

const Tour = require("../models/tourModel"); //MongoDB Document Model

class QueryModifier {
    constructor(query, reqQuery) {
        this.query = query;
        this.reqQuery = reqQuery;
    }

    filter() {
        console.log(this.reqQuery);
        const queryObj = { ...this.reqQuery }; //destruct the URL query object into a new object for a hard-copy
        const toBeExcluded = ["page", "sort", "limit", "fields"];

        toBeExcluded.forEach((el) => {
            delete queryObj[el];
        });

        console.log(queryObj);
        let queryStr = JSON.stringify(queryObj);
        queryStr = queryStr.replace(
            /\b(gte|gt|lte|lt)\b/g,
            (matchedStr) => `$${matchedStr}`
        );

        this.query = this.query.find(JSON.parse(queryStr));
        return this;
    }

    sort() {
        if (this.reqQuery.sort) {
            const sortBy = this.reqQuery.sort.replace(/(,)/g, " ");
            this.query = this.query.sort(sortBy);
        } else {
            this.query = this.query.sort("-createdAt");
        }
        return this;
    }

    limitFields() {
        if (this.reqQuery.fields) {
            const fields = this.reqQuery.fields.replace(/(,)/g, " ");
            this.query = this.query.select(fields);
        } else {
            //Default
            this.query = this.query.select("-__v"); //exclude __v
        }
        return this;
    }

    paginate() {
        const page = this.reqQuery.page * 1 || 1;
        const limit = this.reqQuery.limit * 1 || 10;
        const skip = (page - 1) * limit;
        this.query = this.query.skip(skip).limit(limit);

        return this;
    }
}

exports.getAllTours = async (req, res) => {
    try {
        const features = new QueryModifier(Tour.find(), req.query)
            .filter()
            .sort()
            .limitFields()
            .paginate();
        const tours = await features;

        res.status(200).json({ //<------ Error's "position" is after the second dot.
            status: "success",
            results: tours.length,
            data: { tours },
        });
    } catch (e) {
        res.status(404).json({
            status: "failure",
            message: e.message,
        });
        console.log(e);
    }
};

The error is at the place where I commented with an arrow. And here's the error message:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Topology'
    |     property 's' -> object with constructor 'Object'
    |     property 'sessionPool' -> object with constructor 'ServerSessionPool'
    --- property 'topology' closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (/Users/mirzabicer/Documents/GitHub/complete-node-bootcamp/4-natours/starter/node_modules/express/lib/response.js:1123:12)
    at ServerResponse.json (/Users/mirzabicer/Documents/GitHub/complete-node-bootcamp/4-natours/starter/node_modules/express/lib/response.js:260:14)
    at exports.getAllTours (/Users/mirzabicer/Documents/GitHub/complete-node-bootcamp/4-natours/starter/controllers/tourController.js:84:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I edited that JSON.stringify call to:

let queryStr = '{ "sort": "price,ratingsAverage", "price": { "gte": "300" } }';

So there's literally no JSON.stringify call in my code now. But the error I get is EXACTLY the same.

Hanchen Jiang

The error suggests the problem is in tourController.js on line 84. I guess you are calling JSON.stringify on something that is circular on that line. Try removing that JSON.stringify call.

It seems tours is most likely the problem then. I see it is a QueryModifier. I suppose that is probably not the data you want to return from getAllTours.

You should await the features.query, not the features itself.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TypeError: Converting circular structure to JSON in nodejs

mongodb nodejs - converting circular structure

Converting circular structure to JSON Firebase

TypeError converting circular structure to json at JSON.stringify (<anonymous>)

Angular - TypeError: Converting circular structure to JSON

Converting circular structure to JSON at JSON.stringify ()

express & sequalize Converting circular structure to JSON

Express Middleware: ERROR: TypeError: Converting circular structure to JSON

Elliptic : TypeError : Converting circular structure to JSON

[Vue warn]: Error in render: "TypeError: Converting circular structure to JSON

What is a circular structure in JSON?

Moving code to an exported function results in TypeError: Converting circular structure to JSON

avoiding TypeError: Converting circular structure to JSON

TypeError: Converting circular structure to JSON - find error in json

MongoDB and Express: Type Error: Converting Circular structure to JSON

AWS Cognito - Encountering Error Converting Circular Structure to JSON

Converting circular structure to JSON in window

GraphCool TypeError: Converting circular structure to JSON

how to solve (Uncaught TypeError: Converting circular structure to JSON)

Error: Converting circular structure to JSON

Circular dependency detected, i can't see it

Error Converting Circular Structure to JSON...take 2

Sequelize: TypeError: Converting circular structure to JSON

Reading fixture is throwing error TypeError: Converting circular structure to JSON

Express middleware "TypeError: Converting circular structure to JSON" when sending a non-circular JSON

Nodejs express Converting circular structure to JSON

"TypeError: Converting circular structure to JSON" with GET request

"TypeError: Converting circular structure to JSON" with GET request

Axios TypeError: Converting circular structure to JSON

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive