mongodb - 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.
解决方案
嗯……我想通了。我将发布我发现的答案,以防其他人试图解决这个问题。事实证明,通过更仔细地阅读文档,必须执行返回的 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);
推荐阅读
- php - 如何强制 Heroku 中的网站在访问页面时始终重新加载缓存?
- flutter - 如何防止 iOS 14 Widget 打开应用并响应回调
- python - 二维布尔数组到图像
- unicode - 为什么要对撇号进行这种精心设计的 RTF 编码?
- javascript - 在 Wordpress 块开发的上下文中从道具理解 const 分配的问题
- spring - 在执行@Modifying spring jpa之前注入方法或代码
- html - CSS背景URL源未将图像设置为背景
- python - 从表中提取元素的问题
- python - Python中正确的包结构
- mysql - 创建具有更新多列的存储过程