我使用 Node.js
中的 Express
创建了一个 HTTP API 来进行 CRUD 操作。这部分有效,但是当我发出 GET
请求时,会显示错误:
类型错误:将循环结构转换为 JSON
。
其他 HTTP 方法(例如 POST
和 DELETE
)也可以工作。
这是我的模型:
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);
这是我的 GET
函数:
// [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);
});
});
这是我的用户模型:
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);
编辑:
经过一番挖掘,我发现了问题所在,我有另一个具有以下网址的函数:/:skip/:talk
所以它被执行了,而不是我想要的。
最佳答案
这是因为您无法序列化具有自身引用的对象。
这是一个例子:
const foo = {};
foo.bar = foo
在这里,我创建了一个名为 foo
的对象。我添加了一个名为 bar
的属性,引用 foo
。
那么对象foo
就不能再被序列化了,因为它有一个无限的“属性树”。如果您使用我之前写的示例,这是完全有效的:
foo.bar.bar.bar.bar.bar.bar.bar
唯一的解决方案是手动提取所需的值。您可以使用解构来简化该过程。
关于node.js - NodeJS : TypeError: Converting circular structure to JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470523/