Mongoose: Remove from array[ObjectId]

Created on 24 May 2011  ·  10Comments  ·  Source: Automattic/mongoose

Hello,

How can I remove a ObjectId from a array of ObjectId ?

My model :

var User = new Schema({
    title       : { type : String,  index: true },
    name        : String,
    friends     : [ObjectId],
    join_at     : {type:Date, default:Date.now },
    save_at     : {type:Date, default:Date.now }
});

The function for deleting the objectId : uid

User.findOne({'_id' : self.id}, function(err, me){
    for(var i=0; i<=me.friends.length; i++){
        if (String(me.friends[i])==String(uid)){
            me.friends.splice(i, 1);
            break;                          
        }
    }
    me.save(function(err,us){
        next(err,'kljlmjk'+JSON.stringify(me));
    });     
});                                     

Thanks for your response.

Most helpful comment

Don't use splice.

me.friends.remove(uid);
me.save(callback);

All 10 comments

Don't use splice.

me.friends.remove(uid);
me.save(callback);

That function is beautiful!

Is there a way to do this to multiple documents as following?

User.update({
    friends: uid
}, {
    '$pull': {
        friends: uid
    }
})

Looking for an answer to this same question (above). How do you do this for multiple documents?

wonderful

@bnoguchi Hi, I know this is an old thread, but it is the first post on google (and I did find a solution here).
Just a quick question, though, for completeness sake. Which usage is preferred:

me.friend.remove(uid);
me.save(callback);

Or:

me.friends.pull(uid);
me.save(callback);

Also, is there any more correct way of inserting new "friends" instead of (in short, better alternative for push()):

me.friend.push(uid);
me.save(callback);

Thanks.

Re: first question, doesn't matter, up to personal preference

Re: 2nd question, better in what way?

As-in more efficient/faster.
Also, I noticed that .pop(...) can have problems when emptying an array, throwing "cannot save undefined" field after calling the me.save(callback) function, while remove() works ok - hence me asking.

No, push() should be as fast as you can get while still using save(). You can also do me.update({}, { $push: { friend: uid } }).then(), that will be marginally faster by bypassing middleware, validation, etc. but it won't improve overall latency too much.

Re: the pop() problems, can you open up a separate issue with a stack trace and a script that reproduces this issue please?

Was this page helpful?
0 / 5 - 0 ratings