I'm trying to use mongoose's built in indexOf() method to see if an object id exists in a doc array. But it does not appear to work with object ids, even though the documentation says it should.
var UserSchema = new Schema({
, following : [{ type: Schema.ObjectId, ref: 'User'}]
, followers : [{ type: Schema.ObjectId, ref: 'User'}]
});
This is giving me -1
user1.followers.indexOf(user2._id);
For the following data:
console.log( user1.followers ) # => [ '505e2f1de888c7d701000001' ]
conosle.log( user2._id ) # => 505e2f1de888c7d701000001
console.log( user1.followers.indexOf( user2._id ) ) # => -1
I have also tried passing just user2 object, but same problem:
console.log( user1.followers.indexOf( user2 ) ) # => -1
I should be seeing 1 in the last log here, not -1.
What am I doing wrong?
Here is the mongoose documentation: http://mongoosejs.com/docs/api.html#types_array_MongooseArray-indexOf
Old question, but this bit me recently so I'll post my solution for others burning the midnight oil:
user1.followers.indexOf(user2._id.toString());
I found the problem. I was using the user stored in session, not user object from db. Also, it infact does have to be an object id that is passed:
User.findById(req.session.userid, function(err, user){
user2.isFollowing = user.following.indexOf(user2._id);
});
Storing objects in session is bad. Should always retrieve them from db so they don't get stale and you have a true mongoose doc object, not a json object from redis store.