2015-04-27 178 views
2

我试图从所有具有对它的引用的集合中删除一个用户标识。我从表单中提取用户标识,并希望删除每个业务集合中的每个引用。我知道下面的查询不起作用,但它显示了我目前的做法。使用Nodejs从MongoDB中删除项目

db.collection('business', function (err, allBus){ 
    allBus.update({}, { $pull: {followers: { userID } } }); 
}); 

这是我的数据,任何想法?

{ 
    "_id" : ObjectId("55355d0ab063708c0b73809e"), 
    "address" : "Donegal", 
    "businessName" : "burkes shoes", 
    "email" : "[email protected]", 
    "followers" : [ 
      ObjectId("55300f5208224af428d1beaf"), 
      ObjectId("553129666252d2fc0a4634e4") 
    ], 
    "gpsLat" : "55.1763595", 
    "gpsLong" : "-7.7923", 
    "homeDomain" : "www.burkes.ie", 
    "imgpath" : "\\images\\uploads\\57461Burkes_logo_1429560586607.jpg", 
    "password" : "1", 
    "role" : "business" 
} 
+0

你想删除整个记录还是只删除''followers''的数据?还匹配'_id“字段? –

+0

我想从每个实例业务 – user2947979

+0

中只删除一个id(表单中的userID),但我并不清楚。如果'id ='55355d0ab063708c0b73809e''那么会从样本中给出的'data'中删除什么。也为这个值'55300f5208224af428d1beaf'。 –

回答

1

如果userID是您需要在您的查询中使用它之前,首先将它转换到对象ID字符串。像这样的东西应该做的魔力:

var ObjectID = require("mongodb").ObjectID, 
    userID = new ObjectId("55300f5208224af428d1beaf"); 
/* 
    if userID is a string then this will work 
    var userID = new ObjectId(userID); 
*/ 
db.business.update(
    {"followers": userID}, 
    { 
     "$pull": { "followers": userID } 
    }, 
    { multi: true } 
); 

上面的查询会比一个更新更好的性能,而无需查询为那些在他们的追随者阵列与userID值的元素它首先过滤文档,然后更新匹配通过从数组中提取ObjectID值的文档。