Mongoose - remove multiple documents in one function call

懵懂的女人 提交于 2019-12-12 10:28:42

问题


In documentation there's deleteMany() method

Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});

I want to remove multiple documents that have one common property and the other property vary. Something like this:

Site.deleteMany({ userUID: uid, id: [10, 2, 3, 5]}, function(err) {}

What would be the proper syntax for this?


回答1:


I believe what youre looking for is the $in operator:

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err) {})

Documentation here: https://docs.mongodb.com/manual/reference/operator/query/in/




回答2:


You can also use.

Site.remove({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err, response) {});



回答3:


Yes, $in is a perfect solution :

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5] } }, function(err) {})




回答4:


I had to change id to _id for it to work:

Site.deleteMany({ _id: [1, 2, 3] });

This happens if no id is defined and the default one is used instead:

"Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor." mongoose docs



来源:https://stackoverflow.com/questions/44467318/mongoose-remove-multiple-documents-in-one-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!