mongoose - 检查数组中是否存在ObjectId

p0l*_*ris 20 contains mongoose mongodb node.js

以下是一个示例模型:

UserModel == {
    name: String,
    friends: [ObjectId],
}
Run Code Online (Sandbox Code Playgroud)

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...
    })
})
Run Code Online (Sandbox Code Playgroud)

在这种情况下,条件'about.id in user.friends`似乎总是错误的.怎么样?这与ObjectId的类型或它的保存方式有关吗?

注:ObjectId简称Schema.ObjectId; 我不知道这本身是不是一个问题.

Joh*_*yHK 41

如果about.id是ObjectID的字符串表示形式并且user.friends是ObjectID 的数组,则可以使用以下命令检查about.id数组是否在数组中Array#some:

var isInArray = user.friends.some(function (friend) {
    return friend.equals(about.id);
});
Run Code Online (Sandbox Code Playgroud)

some调用将遍历user.friends数组,调用equals每个数组以查看它是否匹配about.id并在找到匹配时立即停止.如果找到匹配则返回true,否则返回false.

你不能使用更简单的东西,indexOf因为你想要按值而不是通过引用来比较ObjectID.