Joe
Joe

Reputation: 4234

Mongoose, pull from subdocument

This is my document:

{ 
  password: '87654321',
  title: 'Organization A',
  members: 
   [ { tier: 1,
       joinedDate: Sun May 12 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d56 
     },
     { tier: 2,
       joinedDate: Sat May 11 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d57 
     },
     { tier: 3,
       joinedDate: Fri May 10 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d58 
     }
    ]
}

I want to write a query that pulls a member with a given user _.id

The pull command is probably what I should use

http://mongoosejs.com/docs/api.html#types_array_MongooseArray-pull

mongoose.model('organization').findOne({_id:user.organization}, function(err, org){
      org.members.pull({'user._id':user._id});
      org.save();
    })

It's not working. What am I doing wrong?

Update

My schema:

var organizationSchema = new Schema({
  title: String,
  password: { type: String, required: true, index: { unique: true } },
  members: [
    {
      tier: { type: Number, required: true, min:1, max:4},
      joinedDate: Date,
      user:{
        type: Schema.ObjectId,
        ref: 'user',
        required: true,
        unique:true
      }
    }
  ]
});

Upvotes: 2

Views: 5780

Answers (2)

pedrommuller
pedrommuller

Reputation: 16066

I don't see any id referenced in your members array, remove _id and do it directly to your user property since that's what is on the schema.

mongoose.model('organization').findOne({_id:user.organization}, function(err, org){
      org.members.pull({'user':user._id});
      org.save();
    })

EDIT: maybe this one

mongoose.model('organization').update({ _id: user.organization }, {$pull: 
{members.user: user._id}}, {}, function(err, numAffected){
 //check numAffected

});

try that out!

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311935

It appears that the MongooseArray#pull method only works if your elements have _id properties.

I find it easier to use direct calls to update to avoid these sorts of surprises:

mongoose.model('organization').update(
    {_id: user.organization},
    {$pull: {members: {user: user._id}}},
    function(err, numAffected) { ... }
);

Upvotes: 13

Related Questions