MongooseArray#indexOf不能使用对象标识符
我试图使用在indexOf()方法中build立的mongoose来查看对象ID是否存在于doc数组中。 但是它似乎不能用于对象id,尽pipe文档说它应该。
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。
我究竟做错了什么?
这里是mongoose文档: http : //mongoosejs.com/docs/api.html#types_array_MongooseArray-indexOf
老问题,但最近这个问题,所以我会张贴我的解决scheme为其他人燃烧午夜油:
user1.followers.indexOf(user2._id.toString());
我发现了这个问题。 我正在使用存储在会话中的用户,而不是来自数据库的用户对象。 此外,事实上确实必须是传递的对象ID:
User.findById(req.session.userid, function(err, user){ user2.isFollowing = user.following.indexOf(user2._id); });
在会话中存储对象是不好的。 应该总是从数据库检索他们,所以他们不会过时,你有一个真正的mongoose文档对象,而不是从redis商店的JSON对象。