如何使用mongoose在MongoDB中推送嵌入式模式中的元素?
我有些困惑。下面是我的如何使用mongoose在MongoDB中推送嵌入式模式中的元素?,mongodb,mongoose,mongoose-schema,Mongodb,Mongoose,Mongoose Schema,我有些困惑。下面是我的客户模式: [ { _id:'xxx', 名称:“AAAA”, 电子邮件:“adfasd”, 电话号码:'', 密码:“abc123”, 订单:[ { _id:'xxx', 餐厅标识:“abc”, 餐厅名称:“abc”, 地点:[77.623022,12.936933], 地址1:“”, 地址2:“”, img_url:“”, 项目:[ { _id:'xxx', 价格:250, 名称:“奶酪汉堡”, 数量:3, 蔬菜:错 }, { _id:'xxx', 价格:160, 名
客户
模式:
[
{
_id:'xxx',
名称:“AAAA”,
电子邮件:“adfasd”,
电话号码:'',
密码:“abc123”,
订单:[
{
_id:'xxx',
餐厅标识:“abc”,
餐厅名称:“abc”,
地点:[77.623022,12.936933],
地址1:“”,
地址2:“”,
img_url:“”,
项目:[
{
_id:'xxx',
价格:250,
名称:“奶酪汉堡”,
数量:3,
蔬菜:错
},
{
_id:'xxx',
价格:160,
名称:"春卷",,
数量:4,
维格:没错
}
]
}
]
}
];代码>您应该使用插入新元素。它还避免了比赛条件
router.patch('/order/:cust_id', async (req, res) => {
const id = req.params.cust_id;
// Getting new order details
const order = {
restaurant_id: req.body.restaurant_id,
restaurant_name: req.body.restaurant_name,
location: {type: 'Point', coordinates: req.body.location},
address_1: req.body.address_1,
address_2: req.body.address_2,
img_url: req.body.img_url,
items: req.body.items
};
// Updating it
Customer.findByIdAndUpdate(
id,
{$push: {orders: order}}
)
.then(() => res.json('Orders updated Successfully'))
.catch((err) => res.status(400).json('Error: ' + err));
});
module.exports = router;