mongoose 无法从Mongodb文档中保存的对象数组中获取对象的属性

uxh89sit  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(144)

我正在为一个电子商务网站创建一个购物车,并决定在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
  }
]


当我试图访问cartItems数组时,它告诉我对象未定义,但当我检查mongodb控制台时,数组中有我试图访问的cartItem

console.log(item.cartItems[0])


总是返回此错误

console.log(item.cartItems[0])
                          ^

TypeError: Cannot read properties of undefined (reading '0')


这是同样的方式,我访问一个数组的项目在另一个模式,我有它的工作正常,唯一的区别是它的数组字符串不是对象。任何帮助是感激!

chy5wohz

chy5wohz1#

你的item是一个数组,所以我假设你使用Model.find()来定位你的Cart
当你执行Model.find()时,mongoose期望0个或更多的结果,所以总是会返回一个数组(空的或其他的)。
要记录cartItems[0],您需要执行以下操作:

console.log(item[0].cartItems[0]);

字符串
如果你知道你只是在寻找一个购物车,那么如果你有Cart._id值,就使用Cart.findById(id),或者如果你在查询另一个字段,就使用Cart.findOne({email: req.body.email})。这两种方法都将返回一个文档,而不是一个数组。

相关问题