mongoose – 检查ObjectId是否存在于一个数组中

以下是一个示例模型:

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

friends对应于一些其他模型的对象的id列表,例如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... }) }) 

在这种情况下,user.friends中的about.id条件似乎总是假的。 怎么样? 这是用ObjectId的types还是保存的方式?

注意: ObjectIdSchema.ObjectId ; 我不知道这是否是一个问题。

如果about.id是ObjectID的string表示,而user.friends是ObjectID的数组,则可以使用Array#some检查about.id是否在数组中:

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

some调用会遍历user.friends数组,每个调用equals都会查找是否匹配about.id ,一旦find匹配about.id下来。 如果find匹配,则返回true ,否则返回false

你不能使用像indexOf这样简单的东西,因为你想通过值比较ObjectIDs,而不是通过引用。

我使用破折号做这样的事情:

 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 } 

我相信这是一个JavaScript问题,而不是一个Node.js / Mongoose的问题 – 所以它不属于它现在的方式。

此外, about.id in user.friends的问题about.id in user.friends指向的对象和user.friends中的对象是不同的, 我相信in检查对象的平等。

无论如何,答案是堆栈溢出可用来检查数组中存在的元素 –

 user.friends.indexOf(about.id) > -1