用Nodejs从MongoDB中删除项目
我试图从所有的引用它的集合中删除一个用户ID。 我从表单中提取用户标识,并希望删除每个业务集合中的每个引用。 我知道下面的查询不起作用,但它显示了我目前的做法。
db.collection('business', function (err, allBus){ allBus.update({}, { $pull: {followers: { userID } } } ); });
这是我的数据,有什么想法?
{ "_id" : ObjectId("55355d0ab063708c0b73809e"), "address" : "Donegal", "businessName" : "burkes shoes", "email" : "info@burkes.ie", "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" }
如果userID
是一个string,则在查询中使用它之前,您需要先将其转换为ObjectID。 像这样的事情应该做的魔术:
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
值来更新匹配的文档。