我正在try 使用Mongoose的加法门函数从Mongoose模式中检索array.我对这个项目使用的是nestjs,但查询是相同的:

const notifications = await this.userRepo.aggregate( [
      { $match: { _id: userId } },
      { $unwind: "$notifications" },
      { $replaceRoot: { newRoot: '$notifications' } }
] );

这里的问题是,每次我得到一个空array.无论文档中包含什么内容.

以下是一个文档示例:

{
  _id: new ObjectId("6471fe4a0045e48a0c6193ba"),
  gateways: [
    {
      _id: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
      name: 'Babylon Dev',
      right: 'owner'
    }
  ],
  __v: 0,
  notifications: [
    {
      type: 'confirm',
      title: 'Gateway whitelist request!',
      description: '6471fe4a0045e48a0c6193ba wants to share data from gateway 5231db1f-b79a-4dc3-a387-6f08ad7b6857 with you.',
      actions: [Array],
      from: '6471fe4a0045e48a0c6193ba',
      subject: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
      status: 'unread',
      _id: new ObjectId("64b6791adbf7bb6eaa528cf2")
    }
  ]
}

有没有人能告诉我,我把这个设在哪里错了?

我想要的结果是获得通知数组:

[
    {
      type: 'confirm',
      title: 'Gateway whitelist request!',
      description: '6471fe4a0045e48a0c6193ba wants to share data from gateway 5231db1f-b79a-4dc3-a387-6f08ad7b6857 with you.',
      actions: [Array],
      from: '6471fe4a0045e48a0c6193ba',
      subject: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
      status: 'unread',
      _id: new ObjectId("64b6791adbf7bb6eaa528cf2")
    }
  ]

此外,获取/更新/删除notifications数组中的一个元素也会有所帮助.

推荐答案

make sure the userId is the same type as what is stored in the database. In your case it is an ObjectId. you can find here how to do it.
playground

const notifications = await this.userRepo.aggregate( [
      { $match: { _id: mongoose.Types.ObjectId(userId )} },
      { $unwind: "$notifications" },
      { $replaceRoot: { newRoot: '$notifications' } }
] );

or you can go the long way without using the utility functions :P
playground

const notifications = await this.userRepo.aggregate( [
      { $match: { $expr: { $eq: [ "$_id", { $toObjectId: userId } ] } } },
      { $unwind: "$notifications" },
      { $replaceRoot: { newRoot: '$notifications' } }
] );

Mongodb相关问答推荐

带dropTarget的MongoDB renameCollection命令是原子的吗

Tableau 与 Mongo DB Atlas by MongoDB 的连接缓存问题

从 Amazon S3(Next.js、Mongodb、Mongoose)删除图像

Mongoose 聚合和多级组

如何为具有相同名称的嵌套字段创建文本索引

根据聚合管道MongoDB Atlas触发器中的条件更新多个字段

mongo shell 命令不接受使用 db 命令

System.FormatException occurred in MongoDB.Bson.dll - XXX is not a valid 24 digit hex string

创建索引需要很长时间

更新 MongoDB 中嵌套实体数组中的属性

无法使用机器 ip 连接到 mongodb

在 Heroku 上使用 Node 读取、写入和存储 JSON

MongoDB .NET 未在 upsert 上生成 _id

mongodb中类型不相等的查询

有没有办法将python对象直接存储在mongoDB中而不序列化它们

Cannot connect to MongoDB errno:61

将 MongoCursor from ->find() 转换为数组

mongoose 使用 $cond 中的 $exists 聚合

MongoDB 和 Robomongo: Can't connect (authentication)

试图从 mongoose 获取Collection 列表