【问题标题】:Using findById to find the id of a schema in an array使用 findById 在数组中查找模式的 id
【发布时间】:2021-04-28 15:54:05
【问题描述】:

嘿,我想知道如何将 findById 用于数组内的模式?例如,我有以下架构:

  const GameSchema = new mongoose.Schema({
  users: [
    {
      user: { type: mongoose.Schema.ObjectId, ref: 'User' },
      role: {
        type: String,
        required: true,
        enum: ['user', 'moderator', 'creator'],
        default: 'user',
      },
    },
  ]
}]

我想用findById之类的mongoose函数来查找用户,比如如下:

  const user = await game.users.findById({ user: req.user.id })

它似乎不起作用,因为 users 不是 mongodb 模型。我知道我可以使用 find() 找到用户,如下所示:

const user = await game.users.find(
  (gameUser) => gameUser.user == req.user.id
)

唯一的问题是gameUser和req.user.id的类型不一样,我不能用'==='。有没有办法遍历数组并使用猫鼬函数findById?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    正如docs 解释的那样,findById 方法:

    通过 _id 字段查找单个文档

    所以你必须使用findOne() 而不是findById()

    另外,要从整个数组中只返回一个字段,您可以在 find 中使用projection

    检查this 示例。此查询通过其 id(即user 字段)查找对象并仅返回对象,而不是整个数组。

    db.collection.find({
      "users": { "$elemMatch": { "user": 1 } }
    },
    {
      "users.$": 1
    })
    

    使用猫鼬你可以做到:

    yourModel.findOne(({
      "users": { "$elemMatch": { "user": 1 } }
    },
    {
      "users.$": 1
    })).then(result => {
      console.log(result)
    }).catch(e => {
      // error
    })
    

    【讨论】:

      猜你喜欢
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2017-07-12
      • 1970-01-01
      • 2012-07-10
      • 2017-07-18
      • 2023-01-26
      相关资源
      最近更新 更多