Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose — check if ObjectId exists in an array

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 < abouts.length){
                doStuff(index + 1)
            }
        }
        doStuff(0) // recursively...
    })
})

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.

like image 865
p0lAris Avatar asked Nov 02 '13 00:11

p0lAris


People also ask

How do you find if an element exists in an array in mongoose?

In your case you could try: Person. find({ members: { $elemMatch: { id: id1 } } });

What is ObjectID in mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

Is Mongoose _ID unique?

m has _id set. Does mongoose guarantee it's unique by querying mongo while creating model object? It does. One part of id is a random hash and another is a unique counter common accross collections.

What type is Mongoose _ID?

option: _id Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you don't want an _id added to your schema at all, you may disable it using this option.


2 Answers

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.

like image 51
JohnnyHK Avatar answered Oct 21 '22 00:10

JohnnyHK


I use lo-dash and do something like that :

var id_to_found = '...';
var index = _.find(array, function(ch) {
     return ch == id_to_found ;
});
if ( index!=undefined ) {
     // CHILD_ALREADY_EXISTS
} else {
     // OK NOT PRESENTS
}
like image 3
gperreymond Avatar answered Oct 21 '22 00:10

gperreymond