![](/img/trans.png)
[英]Getting error "Converting circular structure to JSON" while working with express,mongodb
[英]Getting a JSON circular structure error when updating a model's field
我正在构建一个带有 NodeJS 的电子商务 web 应用程序和 MongoDB。我正在处理 API,用于将产品 ID 和数量存储在作为用户购物车的数组中。
这是用户 model:
const userSchema = mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
username: {
type: String,
required: true
},
access_level: {
type: Number,
default: 1
},
cart: {
type: [cartProductSchema],
default: []
}
})
这是 cartProductSchema 的 model:
const cartProductSchema = new mongoose.Schema({
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
},
quantity: {
type: Number,
required: true,
validate: { validator: Number.isInteger }
}
}, { _id: false })
这是产品的 model:
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
stock: {
type: Number,
required: true,
validate: { validator: Number.isInteger }
}
}, {timestamps: true})
这是错误所在的路由器的片段:
// Add product to user's cart
const product = await Product.findOne({_id: req.body.product_id})
if (!product) {
return res.status(http.statusNotFound).json({
errors: [{ msg: "Invalid product id" }]
})
}
let cart = user.cart.slice()
cart.push({ product_id: product._id, quantity: req.body.quantity })
user.cart = cart // this is the line that causes the error
await user.save()
res.json({ msg: "Product added to cart" })
当我尝试将带有product_id
和quantity
的 JSON object 推送到用户的购物车时出现错误。 导致它的 JSON object 中有一个循环引用,但我不知道我做错了什么。 错误堆栈跟踪并不是真的这是我得到的错误:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property '__parentArray' -> object with constructor 'Array'
--- index 0 closes the circle
at stringify (<anonymous>)
如果我取消注释user.cart = cart
行,那么我不会收到此错误。 当我尝试更新购物车字段时,出现此错误。 我尝试以不同的格式更新购物车字段,但都失败了。
我尝试直接推送到购物车字段,但出现相同的错误: user.cart.push({ product_id: product._id, quantity: req.body.quantity})
我还尝试使用 MongoDB 查询直接更新购物车,但我仍然遇到相同的错误:
await User.updateOne(
{_id: user._id},
{ $push: { cart: { product_id: product._id, quantity: req.body.quantity } }}
)
我想出了问题所在。 抱歉,添麻烦了。 我应该提到我正在用玩笑测试来测试 API。 原来测试中有一个错误,在将--detectOpenHandles
标记添加到 npm 测试脚本后,我能够进行调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.