使用猫鼬将对象数组添加到子文档
Posted
技术标签:
【中文标题】使用猫鼬将对象数组添加到子文档【英文标题】:Adding An array of Objects to a subdocument using mongoose 【发布时间】:2021-09-08 11:49:30 【问题描述】:我正在使用 mongoose 在 mongoDB 中添加一组对象作为子文档。我无法遍历数组来保存它。
以下是请求数据:
"order" :
[
"price": "50",
"quantity" : "3",
"vegId": "60c8b471e12c801e54b7ee59",
"vegName": "Tomato"
,
"price": "50",
"quantity" : "3",
"vegId": "60c8b471e12c841e54b7ee59",
"vegName": "Onion"
],
"userId" : "60cb597f1edc34385060c288",
"orderTotal":"350",
"createdOn" : "21-6-2021"
这是我的控制器:
exports.confirmOrder = (req, res, next) =>
// console.log(req.body);
// res.status(201).json(
// message: " Message Going"
// )
const orderData = req.body.order;
console.log(orderData);
const order = new Orders(
userId: req.body.userId,
orderTotal: req.body.orderTotal,
vegetables: [
vegId: orderData[0].vegId,
quantity: orderData[0].quantity,
price: orderData[0].price,
vegName: orderData[0].vegName
]
);
order.save().then(result =>
res.status(201).json(
message: "Oder Confirmed"
);
).catch(error =>
console.log(error);
res.status(501).json(
message: " An Error has occured"
)
);
;
如何遍历蔬菜中的请求数据。
【问题讨论】:
只需赋值vegetables: orderData
,无需循环迭代。
谢谢哥们..很有帮助..
【参考方案1】:
您不需要迭代。基本上,您需要分配蔬菜数据,如下所示:
const data =
"order": [
"price": "50",
"quantity": "3",
"vegId": "60c8b471e12c801e54b7ee59",
"vegName": "Tomato"
,
"price": "50",
"quantity": "3",
"vegId": "60c8b471e12c841e54b7ee59",
"vegName": "Onion"
],
"userId": "60cb597f1edc34385060c288",
"orderTotal": "350",
"createdOn": "21-6-2021"
const order = new Orders(
userId: req.body.userId,
orderTotal: req.body.orderTotal,
vegetables: data.order //Give your vegetables data here
);
【讨论】:
谢谢哥们...很有帮助【参考方案2】:我想出了这样的事情:-
exports.confirmOrder = (req, res, next) =>
const orderData= req.body.order;
const data = [];
orderData.forEach((orders)=>
data.push(
vegId:orders.vegId,
quantity: orders.quantity,
price: orders.price,
vegName:orders.vegName
);
);
const order = new Orders(
userId: req.body.userId,
orderTotal: req.body.orderTotal,
vegetables: data
);
order.save().then(result =>
res.status(201).json(
message: "Oder Confirmed"
);
).catch(error =>
console.log(error);
res.status(501).json(
message:" An Error has occured"
)
);
;
【讨论】:
以上是关于使用猫鼬将对象数组添加到子文档的主要内容,如果未能解决你的问题,请参考以下文章