我正在为一个Electron 商务网站创建一个购物车,并决定在Mongodb中为用户存储购物车项目.我可以毫无问题地存储项目,并在Mongodb中显示,但是当我试图从单个项目中获取属性时,它说对象没有定义.
这是购物车的架构
const cartSchema = new Schema(
{
email: {
type: String,
required: true,
},
cartItems: [
{
itemName: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
itemPicture: {
type: String,
required: true,
},
},
],
},
{
timestamps: true,
}
但是当我得到一个用户购物车并登录到控制台时,它看起来是这样的
[
{
_id: new ObjectId("123_documentID_123"),
email: 'users_email',
cartItems: [ [Object] ],
createdAt: 2023-11-19T08:36:38.817Z,
updatedAt: 2023-11-19T08:36:38.817Z,
__v: 0
}
]
当我try 访问cartItems数组时,它告诉我对象未定义,但当我判断MongoDB控制台时,数组中有我试图访问的cartItem
console.log(item.cartItems[0])
始终返回此错误
console.log(item.cartItems[0])
^
TypeError: Cannot read properties of undefined (reading '0')
这与我在另一个模式中访问数组的项的方式相同,它工作得很好,唯一的区别是它是一个字符串数组,而不是对象.如有任何帮助,我们不胜感激!