简体   繁体   中英

Getting a JSON circular structure error when updating a model's field

I am building an e-commerce web application with NodeJS with express and MongoDB. I working on an API for storing a product id and quantity in an array that is the user's cart.

This is the user 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: []
    }
})

This is the model for cartProductSchema:

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 })

This is the model for the Product:

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})

Here is the snippet of the router where the error is.:

// 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" })

I am getting an error when I try to push a JSON object with product_id and quantity into a user's cart. There is a circular reference in the JSON object that's causing it, but I can't figure out what I did wrong. The error stack trace doesn't really Here is the error I get:

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>)

If I uncomment, user.cart = cart line, then I don't get this error. The moment I try to update the cart field, I get this error. I tried updating the cart field in different formats, but all failed.

I tried directly pushing to the cart field, yet I get the same error: user.cart.push({ product_id: product._id, quantity: req.body.quantity})

I also tried to directly update the cart with a MongoDB query, but I still get the same error:

await User.updateOne(
    {_id: user._id}, 
    { $push: { cart: { product_id: product._id, quantity: req.body.quantity } }}
)

I figured out what the problem was. Sorry for the trouble. I should've mentioned I was testing the API with jest tests. Turns out there was an error in the tests, that I was able to debug after adding a --detectOpenHandles tag to the npm test script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM