gpt4 book ai didi

java - 'Users' 以外的集合中的 User.findOne()

转载 作者:行者123 更新时间:2023-11-30 05:24:05 25 4
gpt4 key购买 nike

我编写了一个具有电子邮件验证逻辑的应用程序,并在用户注册时触发它。我使用两种 Mongoose 模型:一种用于记录用户的数据,另一种用于身份验证 token 。在 token 架构中,我获取用户的 ID。

enter image description here

在我的用户 Controller 中,当应用程序需要验证之前发送给用户的 token 时,该 token 将被识别,之后我必须找到记录在其 Mongo 集合中的 token 架构中的用户 ID。为此,我有一个 User.findOne() 函数。

我想要做的是获取存储在 token 集合中的 _userId:ObjectId("some-userid-number"),但我必须在函数内部执行类似的操作

User.findOne({ _userID: mongoose.Schema.Types.ObjectId._userID, ref: 'Token' })

那么,如何获取 Token 模型中存储为 ObjectId 的 _userId 呢?

非常感谢!

最佳答案

如果 Mongoose 模型是用 refs 定义的、findOne/findAll 可以使用 populate 连接多个集合中的数据。请注意,使用 populate 将导致多个查询发送到 mongodb。

Token
.findOne({ token })
.select("_userId")
.populate({
path: '_userId',
select: 'firstName', // Specify the necessary user properties
options: { lean: true }
})
.lean()
.exec();

该请求可以表述为 aggregation query如果性能很重要。此请求将导致将单个查询发送到 mongodb。

Token
.aggregate([
{$match: {
token
}},
{$lookup: {
from: 'users', // the name of the user collection
localField: '_userId',
foreignField: '_id',
as: 'user'
}},
{$project: {
// Specify the necessary user properties in the projection
firstName: '$user.firstName'
}}
])
.exec()

记住在Token(_userId)上创建索引

关于java - 'Users' 以外的集合中的 User.findOne(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com