0

Lets say I have the following schema in Mongoose:

var OrganisationSchema = mongoose.Schema({
  name:       { type: String },
  users:      [ UserSchema ]
});

var UserSchema = mongoose.Schema({
  name:       { type: String, required: true },
  email:      { type: String, required: true }
});

And I saw this example in the docs of mongoose

doc.array.pull(ObjectId)
doc.array.pull({ _id: 'someId' })
doc.array.pull(36)
doc.array.pull('tag 1', 'tag 2')

Therefore I wonder why this function does not work:

OrgSchema.methods.removeUser = function(mail, onRemoveError, onRemoveSucess) {
  var org = this;
  org.users.pull({email: mail});
  org.save(function(err) {
    if(err) {
      onRemoveError(err);
    } else {
      onRemoveSuccess(org); // Gets called but has not removed the user
    }  
  });
};

This kind of pull does not work and I wonder why? Most of the question threads here on stackoverflow refer to the mongodb pull method for doing this sort of thing:

Org.update( { _id: orgid }, { $pull: { candidates: { email: mail }}});

Is this the correct way to go? Can´t I pull directly on a document array?

6
  • I believe you are on the right track. Implementing a method at the document level makes this very efficient. Commented Apr 17, 2015 at 8:23
  • @ZeMoon I edited my question after trying this implementation. Commented Apr 17, 2015 at 9:44
  • Log org.users just after org.users.pull(). Is your change taking place? Commented Apr 17, 2015 at 10:56
  • Solved it by using org.candidates.pull(id). I could use id instead but not the query: {email: mail} Commented Apr 17, 2015 at 11:56
  • 1
    Okay. The mongoose method only expects an id. If you want to base it on a query, you will have to use update instead. Commented Apr 17, 2015 at 11:58

1 Answer 1

1

I solved it by using the org.candidates.pull(id) as specified in the documentation. Query parameters did not seem to work.

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.