node.js - NodeJS: TypeError: Converting circular structure to JSON
问题描述
I made a HTTP API using Express
in Node.js
for CRUD operations. This works partly, but when I make a GET
request an error shows up:
TypeError: Converting circular structure to JSON
.
Other HTTP methods (e.g. POST
and DELETE
) do work.
This is my model:
const mongoose = require('mongoose');
const coment = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
text: {type: String, required: true},
author_coment: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
date: {type: Date, default: Date.now}
});
const vote = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
author_vote: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
vote: {type: Boolean, required: true},
date: {type: Date, default: Date.now}
})
const book = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: {type: String, required: true},
author: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
sinopsis: {type: String, required: true},
text: {type: mongoose.Schema.Types.ObjectId, ref: 'Text'},
creation_date: {type: Date, default: Date.now},
cover: {type: String},
coments: [coment],
votes: [vote]
});
module.exports = mongoose.model('Book', book);
This is my GET
function:
// [GET: Book info]
router.get('/info/:book_id', function (req, res) {
Book.findById(req.params.book_id, (err, book) => {
if (err) return res.status(500).send(err);
res.status(200).send(book);
});
});
Here is my User model:
const mongoose = require('mongoose');
const user = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: {type: String, required: true},
email: {type: String, required: true},
password: {type: String, required: true}
});
module.exports = mongoose.model('User', user);
Edit:
After some digging, I found out what was the problem, I had another function that had this url: /: skip/: talk
so it was executed that one instead of what I wanted.
解决方案
这是因为您无法序列化引用自身的对象。
这是一个例子:
const foo = {};
foo.bar = foo
在这里,我创建了一个名为foo
. 我添加了一个名为bar
references的属性foo
。
然后对象foo
不能再被序列化,因为它有一个无限的“属性树”。如果您使用我之前写的示例,这是完全有效的:
foo.bar.bar.bar.bar.bar.bar.bar
唯一的解决方案是手动提取您需要的值。您可以通过使用解构来简化该过程。
推荐阅读
- javascript - 如何使用 OnClientClick 事件禁用按钮并启用 OnClick 事件并运行服务器端代码?
- c# - Nancy and razor,“找不到类型名称或命名空间..”
- unity3d - 实例化游戏对象并将其放置在错误位置的场景中
- ruby - 在 Chef 中订阅/通知
- javascript - 多文件输入删除 NET.Core 中的特定文件 Gmail 样式
- ramda.js - 通过管道传递多个参数和最后一个函数的结果
- python - 如何从 Python 中的目录中获取文件?
- python - 使用 matplotlib 在 Python 中绘制热图
- node.js - 如何从通过 AWS API 以字符串格式传入的多部分/表单数据中提取 FROM、TO、SUBJECT、BODY、ATTACHMENT 字段(包含 \n\r)
- java - Eclipse e4 应用程序 - 包含在插件中时找不到 ContextFactory