即使数据不匹配,在数组中嵌套 属性 的集合文档上的 Mongoose findOne() 也会解析

Mongoose findOne() on collections's document having nested property in array resolves even when the data doesn't match

假设我有一个用户在数据库中的令牌很少。其中一个令牌可以访问:'unauth',其他令牌可以访问:数据库中的 'auth'。我正在尝试通过其中一个令牌获得访问权限,我正在使用的令牌...在数据库中具有 'unauth' 的访问权限。因此,理想情况下,不应使用该特定令牌检索用户信息。为什么 User.findOne() 仍然得到解决 ??

用户快照

{
"_id" : ObjectId("5a56798ebf68677d469c8226"),
"updatedAt" : ISODate("2018-01-10T20:43:30.895Z"),
"createdAt" : ISODate("2018-01-10T20:37:34.081Z"),
"email" : "test@testing.com",
"password" : "somepwd",
"tokens" : [ 
    {
        "access" : "unauth",
        "token" : "dfdgdgfgdfgdfgdfgfdgfddfg",
        "_id" : ObjectId("5a56798ebf68677d469c8227")
    }, 
    {
        "access" : "auth",
        "token" : "gjhjjjhhhjhhjjhjhjhjjjjjjjjjghfgh",
        "_id" : ObjectId("5a567a0ebf68677d469c8229")
    }
],
"__v" : 4
}


User.findOne({
 '_id': '5a56798ebf68677d469c8226',
 'tokens.access': 'auth',
 'tokens.token': 'dfdgdgfgdfgdfgdfgfdgfddfg'
})

显然我设法做到了....,它显示结果的原因是因为 Mongodb 找到数组中具有任何 属性 的每个元素。对于任何偶然发现它的人......正如文档中引用的那样,在嵌套数组元素上搜索语法是 => ("arrayName":{ $elemMatch: {"key1" : "value1", "key2" : "value2"}, "key":"value"});