如何在 mongodb 中获取用户 id 并在 jwt 中使用它?

Posted

技术标签:

【中文标题】如何在 mongodb 中获取用户 id 并在 jwt 中使用它?【英文标题】:How to get user id in mongodb and use it in jwt? 【发布时间】:2021-08-11 13:02:46 【问题描述】:

TypeError:无法读取未定义的属性“_id”

collection.insertOne(username: username, password: password).then((err, user) => 
    const payload = user._id
    jwt.sign(payload, 'aspect', (err, token) => 
        console.log(token)
    )
)

【问题讨论】:

console.log(err) 得到什么? 从 then 承诺中删除 err 并使用 .catch(err) 【参考方案1】:

InsertOne 有 3 个可能的签名:

insertOne(docs: Object, callback: MongoCallback<InsertOneWriteOpResult>): void;
insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult>;
insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback<InsertOneWriteOpResult>): void;

您正在使用 Promise 签名,因为您没有提供回调函数。

所以返回值是InsertOneWriteOpResult,看起来怎么样?


    insertedCount: number;
    ops: Array<any>;
    insertedId: ObjectID;
    connection: any;
    result:  ok: number; n: number ;

意味着您需要将代码更改为首先只有 1 个输入用于承诺解析,然后使用 insertedId 而不是 _id,如下所示:

collection.insertOne(username: username, password: password).then((userInsertResult) => 
    const payload = userInsertResult.insertedId
    jwt.sign(payload, 'aspect', (err, token) => 
        console.log(token)
    )
)

【讨论】:

以上是关于如何在 mongodb 中获取用户 id 并在 jwt 中使用它?的主要内容,如果未能解决你的问题,请参考以下文章