【问题标题】:How to use Mongoose queries to filter to the documents that have a specified value inside an array-typed field?如何使用 Mongoose 查询过滤到数组类型字段中具有指定值的文档?
【发布时间】:2021-10-15 13:47:26
【问题描述】:

我知道如何使用Model.findOne,但我希望将Mongoose queries 用于相同的任务。

如何使用 Mongoose 查询来做到这一点?

所以我有这个旧代码:

Notification.find(
  {
    subscribers: user.id
  }
)
...

我正在研究这个替代代码:

const r = await Notification.find()
  .where("subscribers")
  .equals(user.id)
...

但我认为.equals 不适用于这种情况,因为subscribers 是ObjectIds 的数组,而user.id 是基于ObjectId 的字符串。

我搜索了官方 API 文档并没有找到答案。没有错误消息。

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    我找到了the Query.prototype.all method。现在代码如下所示:

    const r = await Notification.find().where("subscribers").all([user.id]);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2017-04-26
      • 2021-04-27
      • 1970-01-01
      • 2021-04-28
      • 2021-07-26
      • 2019-09-08
      相关资源
      最近更新 更多