Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

mongoose — check if ObjectId exists in an array

mongoose — check if ObjectId exists in an array

Problem

Following is an example model:

UserModel == {
    name: String,
    friends: [ObjectId],
}

friends corresponds to a list of id of objects of some other model for example AboutModel.

AboutModel == {
    name: String,
}

User.findOne({name: 'Alpha'}, function(error, user){
    About.find({}, function(error, abouts){ // consider abouts are all unique in this case
        var doStuff = function(index){
            if (!(about.id in user.friends)){
                user.friends.push(about.id);
                about.save();
            }
            if (index + 1 

In this case, the condition 'about.id in user.friends` seems to be always false. How? Is this to do with the type of Objectid or the way it is saved?

Note: ObjectId is short for Schema.ObjectId; I don't know if that's an issue in itself.

Problem courtesy of: p0lAris

Solution

If about.id is a string representation of an ObjectID and user.friends is an array of ObjectIDs, you can check if about.id is in the array using Array#some:

var isInArray = user.friends.some(function (friend) {
    return friend.equals(about.id);
});

The some call will iterate over the user.friends array, calling equals on each one to see if it matches about.id and stop as soon as it finds a match. If it finds a match it returns true, otherwise false.

You can't use something simpler like indexOf because you want to compare the ObjectIDs by value, not by reference.

Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

mongoose — check if ObjectId exists in an array

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×