javascript - User.findOne 在对象解构字符串键中循环

标签 javascript arrays mongodb mongoose object-destructuring

我正在参加在线类(class),其中有一部分讲师说他正在尝试使用 User.findOne 查找/验证用户,并传递一些条件来查找所请求的用户。为了传递值,他使用对象解构。具体代码如下:

const token = req.header("Authorization").replace("Bearer ", "");
const decoded = jwt.verify(token, "secret key here!"); 

// issue is here, look at the second property of the findOne function's argument.
const user=await User.findOne({_id: decoded._id, 'tokens.token': token})

教师正在使用 'tokens.token' 中的字符串键。他的意思是,mongodb 将循环指定的 user 对象中可用的所有 token ,以检查给定的token 是否匹配。

如果您想知道,这里有一个包含 auth token 的单个用户示例:

  {
        "name": "Prottay",
        "_id": "5e27f23b6b549b4c28b8ac35",
        "password": "$2a$08$gUfMwk6TNWViHihrcxjKg.8EXD04lLkGIWXqzrf8wYokdLQXHxpdy",
        "tokens": [
            {
                "_id": "5e27f23b6b549b4c28b8ac36",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2NzYyMTl9.-PWXzlEoPlEZn9F_awtzqrXOtByxUCW9RCdchHF1yKE"
            },
            {
                "_id": "5e280429596e742dcc2f9e30",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2ODA4MDl9.7W-QZ55Cc3NFd_-NPyJ0VW_5F1UVrDWAV4xHX63D6tc"
            },
            {
                "_id": "5e280435596e742dcc2f9e31",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2ODA4MjF9.vppisFiNNC_DYHtGK0IURzEOCCC5zcWl1v9yD6l1D4I"
            }
        ],
        "__v": 3
    },

对我来说,看起来通过使用 'tokens.token': token 讲师正在尝试在用户的 token 数组上循环以匹配正确的 token 。

我说得对吗?如果我是,他怎么能在对象解构中使用循环?

最佳答案

讲师不会使用对象解构来循环数组,而是使用 mongodb 语法在数组中搜索文档,而您事先不知道索引。

If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot (.) and the name of the field in the nested document.

https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#specify-a-query-condition-on-a-field-embedded-in-an-array-of-documents

关于javascript - User.findOne 在对象解构字符串键中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59864108/

相关文章:

javascript - jQuery RTF 编辑器

javascript - 单击标签时防止向链接添加顶点

javascript - 对子值求和并将结果保存到 Javascript 中的 n 叉树中的父级

c - 对指向指针 "array"的指针的单个 malloc 调用导致无效写入

javascript - 更新 Mongoose 中的依赖日期字段

node.js - 如何在 Mongoose 的 upsert 操作中设置更新时间戳?

java - 带条件的 mongotemplate 聚合

javascript - Angular 2 中的 Fetch.js 提示 CORS 请求

javascript - 函数的单向绑定(bind)

php - 如何使用 php 计算图像的 2D DCT?