node.js - NodeJS : TypeError: Converting circular structure to JSON

标签 node.js express mongoose

我使用 Node.js 中的 Express 创建了一个 HTTP API 来进行 CRUD 操作。这部分有效,但是当我发出 GET 请求时,会显示错误: 类型错误:将循环结构转换为 JSON。 其他 HTTP 方法(例如 POSTDELETE)也可以工作。

这是我的模型:

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/

相关文章:

javascript - 以原子方式更新数组项

node.js - 无法提取位置的地理 key

javascript - 嵌套路由请求被解释为对 CSS 文件的请求

javascript - YouTube Api V3 - Videos.update - 禁止错误

javascript - 使用 puppeteer 等待 fs writefile 不会等到文件写入后再继续事件循环

javascript - res.clearCookie 函数不会删除 cookie

node.js - Express 4.x 在 2 分钟后关闭连接

node.js - require() 与 module.require() 在 nodejs 中?

javascript - Mongoose 保存不正确的值

node.js - 在 Mocha 测试期间尝试进行 Mongoose 查询时 promise 超时