类型错误:在 mongoDB/mongoose 中将循环结构转换为 JSON

Aka*_*yam 1 javascript mongoose mongodb node.js

我的代码中出现以下错误。另一件事是,第 3 行的常量“Product”未定义,我不知道为什么。请帮帮我。完整代码位于 github 上的此链接

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/akash/Desktop/Projects/cheaplops/node_modules/express/lib/response.js:1123:12)
at ServerResponse.json (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/response.js:260:14)
at module.exports.getAllProducts (/Users/akash/Desktop/Projects/cheaplops/controllers/productController.js:14:19)
at Layer.handle [as handle_request] (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/layer.js:95:5)
at /Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:335:12)
at next (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:174:3)
at router (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:317:13)
at /Users/akash/Desktop/Projects/cheaplops/node_modules/express/lib/router/index.js:284:7
Run Code Online (Sandbox Code Playgroud)

代码 -

const mongoose = require('mongoose');

const Product = require('../models/productsModel');
const catchAsync = require('../utils/catchAsync');

module.exports.getAllProducts = async (req, res, next) => {
    try {
        // Get all products
        const products = Product.find();

        // console.log(products);

        // Send response
        res.status(200).json({
            status: 'success',
            results: products.length,
            data: {
                products,
            },
        });
    } catch (error) {
        console.log(error);
        res.status(404).json({
            status: 'fail',
            err: error,
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

vis*_*hnu 8

您需要等待查询返回数据才能发送响应。

await您可以在查询前面使用

const products = await Product.find();
Run Code Online (Sandbox Code Playgroud)