使用update mongoDB从objectId数组中删除(Remove from array of objectId using update mongoDB)

编程入门 行业动态 更新时间:2024-10-26 18:30:21
使用update mongoDB从objectId数组中删除(Remove from array of objectId using update mongoDB)

我有一个名为courier的模型,它有一个名为order的数组,order有一些模型顺序的ObjectIds,如何使用update或其他东西从orders数组中删除一个元素?

(例如删除具有特定ID的订单)

这是我的模型:

信使:

var courierSchema = new Schema({ name: { type: String }, orders:[{type:Schema.Types.ObjectId,ref:'order'}], });

我尝试了这段代码,但它失败了:

courier.update({ name: 'Mahan' }, { $pull : { orders: { _id: order._id } } }, (err, count, obj) => { if(err) { console.log(err); return handleError(err, reply); } console.log(count); });

有没有办法做到这一点,不使用查找,删除,然后保存?

I have a model named courier, it has an array named order and orders has some ObjectIds of model order, how can I remove an element from orders array using update or something else ?

(for example removing an order with specific id)

Here is my model:

courier:

var courierSchema = new Schema({ name: { type: String }, orders:[{type:Schema.Types.ObjectId,ref:'order'}], });

I tried this code but it fails :

courier.update({ name: 'Mahan' }, { $pull : { orders: { _id: order._id } } }, (err, count, obj) => { if(err) { console.log(err); return handleError(err, reply); } console.log(count); });

Is there any way to do this not using find, remove and then save ?

最满意答案

这将是实现您尝试的最有效的格式

db.collection.update({<cond to identify document}, {$pull: {'orders': {'id': <id>}}} )

This would be the most efficient format to achieve what you are trying to do

db.collection.update({<cond to identify document}, {$pull: {'orders': {'id': <id>}}} )

更多推荐

本文发布于:2023-07-17 13:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   mongoDB   update   objectId   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!