【问题标题】:TypeError: Converting circular structure to JSON node jsTypeError:将循环结构转换为 JSON 节点 js
【发布时间】:2020-09-14 10:59:23
【问题描述】:

当我尝试通过邮递员获取我的 api 时出现此错误

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

我用猫鼬和快递

const express = require('express')
const Rent = require('../model/rent')
var stringify = require('json-stringify-safe');

route = express()

route.use(express.json());

route.get('/rent', (req,res) => {
    const rents = Rent.find();
    res.send(JSON.stringify(rents))
})

module.exports = route

如果我删除 JSON.stringify 我有同样的问题 提前谢谢你

【问题讨论】:

    标签: node.js json mongoose


    【解决方案1】:

    试试这个:

    
    route.get('/rent', (req,res) => {          
        Rent.find({}).then((rents)=>{
            res.send(rents)
        })           
    })
    

    【讨论】:

      【解决方案2】:

      解决方案 #1

      1. 在模型 Rent 上调用 find 将返回一个 Promise。
      2. 我们需要 await 让 Promise 解决或在出现错误时被拒绝。
      3. 始终将async\await 代码放在try-catch 块中。
      const express = require('express')
      const Rent = require('../model/rent')
      
      route = express()
      
      route.use(express.json());
      
      route.get('/rent', async (req, res) => {
        try {
          const rents = await Rent.find().exec();
          res.send(JSON.stringify(rents));
        } catch (error) {
          res.send({error: error.message});
        }  
      })
      
      module.exports = route;
      

      解决方案 #2:如果您想要 JSON 格式的结果。这就是我的编码方式。

      * node_modules
      * app.js
      * db.js
      * src
        - routes
          - api_router.js
      

      文件path\to\project\app.js

      var express = require('express');
      var path = require('path');
      var cookieParser = require('cookie-parser');
      var logger = require('morgan');
      
      const db = require("./db");
      
      var apiRouter = require('./src/routes/api_router');
      
      var app = express();
      
      app.use(logger('dev'));
      app.use(express.json());
      app.use(express.urlencoded({ extended: false }));
      app.use(cookieParser());
      app.use(express.static(path.join(__dirname, 'public')));
      
      app.use('/api', apiRouter);
      
      module.exports = app;
      

      文件path\to\project\db.js

      const mongoose = require('mongoose');
      const DB_URI = "mongodb://localhost:27017/backend_app";
      const DB_OPTIONS = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true
      }
      
      (async function () {
        try {
          await mongoose.connect(DB_URI, DB_OPTIONS);
          console.log("MONGOOSE: Connected to the database!");
        } catch (error) {
          console.log("MONGOOSE ERROR");
          console.log(error);
        }
      })();
      

      文件path\to\project\src\routes\api_router.js

      const express = require('express');
      const router = express.Router();
      
      const Rent = require('../models/country_model')
      
      router.get('/rent', async (req, res) => {
        try {
          const rents = await Rent.find().exec();
          res.status(200).json({ data: rents });           // <- Check this line.
        } catch (error) {
          res.status(500).json({ error: error.message });  // <- Check this line.
        }
      })
      
      module.exports = router;
      

      为什么是find().exec()

      find().exec() on mongoose 函数将返回一个“真实”的 Promise 对象。 Read this.

      【讨论】:

      • 请使用此../model/rent 文件的内容更新您的问题。
      【解决方案3】:

      Rent.find(); 可能会返回一个Promise,这就是您要在那里进行字符串化的内容。您可能会做的是await Promise 以获得所需的实际值。这应该可以解决问题:

      const express = require('express')
      const Rent = require('../model/rent')
      var stringify = require('json-stringify-safe');
      
      route = express()
      
      route.use(express.json());
      
      route.get('/rent', async (req,res) => {          // Made the controller into an `async` function to be able to use the `await` keyword
          const rents = await Rent.find();             // Await the Promise
          res.send(JSON.stringify(rents))
      })
      
      module.exports = route
      

      【讨论】:

      • 我有同样的错误,这并没有解决它
      • @AdamCole 你的代码和提问者的一样吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2016-01-22
      • 2017-06-29
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多