【问题标题】:User.findOne() in a collection other than 'Users''Users' 以外的集合中的 User.findOne()
【发布时间】:2019-11-23 23:32:36
【问题描述】:

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

在我的用户控制器中,当应用程序需要对之前发送给用户的令牌进行身份验证时,会识别该令牌,然后我必须在其 Mongo 集合中找到记录在令牌模式中的用户 ID。为此,我有一个User.findOne() 函数。

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

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

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

非常感谢!

【问题讨论】:

  • 总结一下。 token值是用户呈现的,查询需要弄清楚token属于哪个userId?
  • 是的,@jorgenkg...就是这样...

标签: java node.js mongoose


【解决方案1】:

如果 Mongoose 模型是用 refs 定义的,findOne/findAll 可以使用 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)上创建索引

【讨论】:

  • 感谢您的建议,@jorgenk。但我必须承认我不明白如何在我的代码中实现它。有没有单行方案可以放到User.findOne()函数中?
  • 我认为我的问题是因为我的所有代码的细节都很差。很抱歉,感谢您的帮助!
【解决方案2】:

答案比我想象的要简单:-)

async confirmationPost (req, res) {
    const token_ = req.body.token;
    await Token.findOne({ token:token_ }, function (err, tokenData) {
       if (!tokenData) {
          return res.status(),
       }
       else 
       {     
       tokenUser = tokenData._userId
       User.findOne({ _id: tokenUser }, function (err, user) {
       // logic-logic
       }

我能够捕获所有令牌集合数据,因此是定义 tha 变量的简单案例 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 2019-09-22
    • 2014-02-13
    • 2020-07-24
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多