2

I'm trying to delete a user id from all collections that have a reference to it. I'm bringing a user id across from the form and want to remove every reference to it in every business collection. I know the below query doesn't work but it shows my current approach.

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

Here is my data, any ideas?

{
    "_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"
}
7
  • you want to delete entire record or only remove data from "followers"? Also match the "_id" field? Commented Apr 27, 2015 at 13:02
  • I want to remove only one id(userID from the form) from every instance business Commented Apr 27, 2015 at 13:05
  • i didn't understand clearly. if id = '55355d0ab063708c0b73809e' then what will be deleted from the data given as sample. Also for this value 55300f5208224af428d1beaf. Commented Apr 27, 2015 at 13:10
  • you want to delete those documents where userID contains in followers ? Commented Apr 27, 2015 at 13:17
  • Yes yogesh, exactly. Commented Apr 27, 2015 at 13:58

1 Answer 1

1

If userID is a string you will need to cast it first to ObjectID before using it in your query. Something like this should do the magic:

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 }
);

The query above will have better performance than an update without a query as it first filters documents that have in their followers array an element with the userID value and then updates the matched documents by pulling the ObjectID value from the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.