首页 > 解决方案 > MongoDB Converting Circular Structure to JSON error

问题描述

I'm trying to query a collection of users using Mongoose in a Node API.

The handler looks like this:

exports.getUsers = async function(req, res, next) {
    try {
        let users = db.User.find();
        return res.status(200).json(users);
    } catch(e) {
        return next(e);
    }
};

This returns an error that reads Converting circular structure to JSON. When I console.log() the results of db.User.find(), I get a Query object. I've checked everything else. All of my other routes are working normally.

标签: mongodbmongoose

解决方案


嗯……我想通了。我将发布我发现的答案,以防其他人试图解决这个问题。事实证明,通过更仔细地阅读文档,必须执行返回的 Query 对象。有两种方法可以执行它——使用回调函数或返回一个承诺(但不能同时使用两者)。我发现这个关于 mongoose 文档中查询的​​页面很有帮助。我的最终处理程序看起来像这样。

exports.getUsers = async function(req, res, next) {
    try {
        db.User.find()
            .then(users => {
                return res.status(200).json(users);
            });
    } catch(e) {
        return next(e);
    }
};

下次我想我会在问之前再挖几分钟。

编辑添加:

找到了第二个解决方案。由于使用了异步函数,我还能够在 try 块中使用以下内容。

let users = await db.User.find();
return res.status(200).json(users);

推荐阅读