1

I am having a schema called ReferralHistory. It contains set of users and array of referred users.

ReferralHistory

var mongoose = require('mongoose');
var refferalHistorySchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        unique: true
    },

    referrals: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }],
});
var ReferralHistoryModel = mongoose.model('ReferralHistory', refferalHistorySchema);
module.exports = {
    referralHistory: ReferralHistoryModel
}

I need to delete a particular user from referrals array in the collection ReferralHistory[Here i only know id of referred user].How can i achieve this?

Edit

Collection enter image description here

I tried

db.referralhistories.update({ "u_referrals": "593281ef966d7f0eeb94db3d" }, { "$pull": { "u_referrals": "593281ef966d7f0eeb94db3d" } });

O/Penter image description here

But document is not updating.

1 Answer 1

8

You use the $pull operator with .update(). So assuming referredId as the value you know

ReferralHistoryModel.update(
  { "referrals": referredId },
  { "$pull": { "referrals": referredId } },
  { "multi": true },
  function(err,status) {

  }
)

Noting the { "multi": true } means the update can be applied to more than one matched document in the collection. If you really only intend to match and update one document then you don't include that option since updating only the first match is the default.

If you want to be more specific and also have the "user" to match, then you can do:

ReferralHistoryModel.update(
  { "user": userId, "referrals": referredId },
  { "$pull": { "referrals": referredId } },
  { "multi": true },
  function(err,status) {

  }
)

And then the match needs both values to be present as opposed to any ReferralhistoryModel documents which matched the referredId you supplied.

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

3 Comments

Thanks for your answer.I have tried your solution.But not getting the result.Updated the question
@Muhsin because you are entering that in the shell/robomongo/whatever. The values are ObjectId and not strings. In the shell you need to use ObjectId("593281ef966d7f0eeb94db3d") in order to match. Mongoose however will cast the type for you.
It got working now.Thank you so much for your help. This is so very helpful to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.