如何使用MongooseJS在MongoDB存储嵌套数据?代码报错求助
解决MongoDB购物车嵌入数组存储的ValidationError问题
问题场景
要存储的样本数据:
{ "id": "242kd", "user_id": "123gsgshsghgshgs6", "product_id_quantity": [ { "product_id": 8, "quantity": 2 }, { "product_id": 7, "quantity": 5 } ] }
使用Postman测试API时收到错误:
{ "message": "ValidationError: product_id_quantity: Cast to Embedded failed for value \"[ { _id: new ObjectId(\"643c330dd33750a122282f3f\") } ]\" (type Array) at path \"product_id_quantity\" because of \"ObjectExpectedError\"Error occuer at the time of cart creation!" }
错误原因
- 模型定义错误:
cartSchema里的product_id_quantity字段被定义为单个嵌入式文档,但实际要存储的是数组类型数据,Mongoose无法将数组转换为单个对象,因此抛出ObjectExpectedError。 - 控制器逻辑错误:控制器只尝试创建单个
productIdQuantity实例,没有遍历请求体中的product_id_quantity数组,且直接取req.body.product_id_quantity.product_id是无效操作(因为它是数组)。 - 数据类型不匹配:样本数据中
product_id是数字类型,但模型里定义为String类型,会触发额外验证错误。
修改方案
1. 修改模型文件(cartModel.js)
将cartSchema中的product_id_quantity改为数组类型,同时修正product_id的类型以匹配样本数据:
const productIdQuantitySchema = mongoose.Schema({ id: String, product_id: { type: Number, required: true }, // 改为Number类型,匹配样本数据 quantity: { type: Number, required: true }, }); const cartSchema = mongoose.Schema({ id: String, userId: { type: String, required: true }, product_id_quantity: [productIdQuantitySchema], // 改为数组形式 });
2. 修改控制器文件(cartController.js)
遍历请求体中的product_id_quantity数组,逐个创建嵌入式文档实例:
exports.createCart = (req, res, next) => { // 遍历商品数量数组,生成对应的嵌入式文档实例 const productItems = req.body.product_id_quantity.map(item => { return new productIdQuantitySchema({ product_id: item.product_id, quantity: item.quantity, }); }); const cart = new Cart({ userId: req.body.user_id, product_id_quantity: productItems, // 传入处理后的数组 }); cart.save().then(result => { res.status(201).json({ message: "Cart Created!", result: result }); }) .catch(err => { res.status(500).json({ message: `${err} Error occurred at the time of cart creation!` }); }); }
3. 验证Postman请求体
保持请求体和样本数据一致即可,无需修改。
内容的提问来源于stack exchange,提问作者Srikrushna
相关产品推荐
相关产品推荐

