如何通过多个标准从数组中抽取多个对象

我有一个情况,我不得不从一个数组中取出多个值的请求。

数据库中的状态

{ "_id" : ObjectId("56fb8fdf5e3227c637891ca8"), "description" : "Testing service", "name" : "test-service", "endpoints" : [ { "uri" : "/api/test1", "method" : "GET", "description" : "test1", "noAuthRequired" : true, "allowedByDefault" : true, "allowedRoles" : ['admin'] }, { "uri" : "/api/test2", "method" : "GET", "description" : "test2", "noAuthRequired" : true, "allowedByDefault" : true, "allowedRoles" : ['admin'] }, { "uri" : "/api/test3", "method" : "GET", "description" : "test3", "noAuthRequired" : true, "allowedByDefault" : true, "allowedRoles" : ['admin'] } ] } 

请求列出我必须从数据库数组中删除的多个端点。 JSON请求的示例:

 { "endpoints": [{ "uri": "/api/test1", "method": "GET" }, { "uri": "/api/test2", "method": "POST" }] } 

当这个请求到达并被处理时,它应该使用URI / api / test1和GET方法删除端点。 它不应该删除带有URI / api / test2和GET GET beacuse请求的端点,应该删除POST / api / test2,并且由于它不存在于DB中,只有GET / api / test1被删除。

我试过这样做,使用mongoose:

 router.route('/services/:id/endpoints').delete(function(req, res) { ... model.service.findOneAndUpdate({ '_id': req.params.id }, { $pull: { 'endpoints': req.body.endpoints } }, function(err, srv) { ... }); }); 

而那什么都不做。

 router.route('/services/:id/endpoints').delete(function(req, res) { ... model.service.findOneAndUpdate({ '_id': req.params.id }, { $pullAll: { 'endpoints': req.body.endpoints } }, function(err, srv) { ... }); }); 

这也没有任何好处。

 router.route('/services/:id/endpoints').delete(function(req, res) { ... model.service.findOneAndUpdate({ '_id': req.params.id }, { $pullAll: { 'endpoints': { $in: req.body.endpoints } } }, function(err, srv) { ... }); }); 

这将删除数据库中的所有端点,它不应该这样做。

我已经决定使用asynchronous:

 var pullCalls = []; req.body.endpoints.forEach(function(endpoint) { pullCalls.push(function(callback) { model.service.findOneAndUpdate({ '_id': req.params.id }, { $pull: { 'endpoints': { 'method': endpoint.method, 'uri': endpoint.uri } } }, function(err, srv) { if (err) return callback(err); callback(err, srv); }); }); }); // TODO: try doing this without async in a single query async.parallel(pullCalls, function(err, srv) { if (err) { res.status(500); res.json({ 'success': false, 'response': err }); } else { res.json({ 'success': true, 'response': 'endpoints_removed' }); } }); 

这工作,但我想在没有asynchronous的单个mongoose查询。 有没有办法做到这一点?

谢谢 :)

你是如此讨厌这个,但是:

 { "$pull": { "endpoints": { "$or": req.body.endpoints } } } 

将工作得很好。

$or操作符希望数据的格式与您提交的格式完全相同。 $pull已经在本质上检查了数组字段元素。

当然, $or意味着“或者”,这基本上意味着“任何符合这些条件的任何东西都需要被拉动”

所以只要req.body.endpoints实际上表示为一个数组,就像你说的那样,那实际上是$or正确的参数