![](/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.