2012-10-17 32 views
2

我试图使用mongoose的内置indexOf()方法来查看对象id是否存在于doc数组中。但它似乎没有与对象id一起工作,即使文档说它应该。MongooseArray#indexOf不与对象id工作

var UserSchema = new Schema({ 
    , following : [{ type: Schema.ObjectId, ref: 'User'}] 
    , followers : [{ type: Schema.ObjectId, ref: 'User'}] 
}); 

这是给我-1

user1.followers.indexOf(user2._id); 

下列数据:

console.log(user1.followers) # => [ '505e2f1de888c7d701000001' ] 
conosle.log(user2._id) # => 505e2f1de888c7d701000001 
console.log(user1.followers.indexOf(user2._id)) # => -1 

我也试图通过user2来自刚对象,但同样的问题:

console.log(user1.followers.indexOf(user2)) # => -1 

我应该在最后看到1记录在这里,而不是-1。

我在做什么错?

这是猫鼬文档: http://mongoosejs.com/docs/api.html#types_array_MongooseArray-indexOf

+0

参数必须是对象。 'user1.followers.indexOf(user2);' – Joonas

+0

仍然不起作用。 - isFollowing ['50680445639190c06a000002','505e2f1de888c7d701000001'] 505e2f1de888c7d701000001 -1 – chovy

回答

0

我发现这个问题。我正在使用存储在会话中的用户,而不是来自数据库的用户对象。此外,事实上确实必须是通过的对象ID:

User.findById(req.session.userid, function(err, user){ 
    user2.isFollowing = user.following.indexOf(user2._id); 
}); 

在会话中存储对象是不好的。应始终从db中检索它们,以免它们过时,并且您拥有一个真正的猫鼬doc对象,而不是来自redis存储区的json对象。

4

老问题,但是这个最近咬我,所以我会后我对别人挑灯解决方案:

user1.followers.indexOf(user2._id.toString());