首页 > 解决方案 > 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/: talkso it was executed that one instead of what I wanted.

标签: node.jsexpressmongoose

解决方案


这是因为您无法序列化引用自身的对象。

这是一个例子:

const foo = {};
foo.bar = foo

在这里,我创建了一个名为foo. 我添加了一个名为barreferences的属性foo

然后对象foo不能再被序列化,因为它有一个无限的“属性树”。如果您使用我之前写的示例,这是完全有效的:

foo.bar.bar.bar.bar.bar.bar.bar

唯一的解决方案是手动提取您需要的值。您可以通过使用解构来简化该过程。


推荐阅读