【问题标题】:Querying objects for an array of attributes in Mongoose在 Mongoose 中查询一组属性的对象
【发布时间】:2021-11-06 00:55:54
【问题描述】:

我正在尝试获取一组用户的聊天记录。 聊天模式的定义如下:

const ChatSchema = new Schema<IChatSchema>(
  {
    messages: [
      {
        type: Schema.Types.ObjectId,
        ref: "MessageSchema",
      },
    ],
    participants: [
      {
        type:Schema.Types.ObjectId,
        ref: "UserSchema",
      }
    ]
  },
  {
    timestamps: true,
  }
);

我有两个用户名“A”和“B”,我想查询这两个用户的常用聊天记录。知道怎么做吗?

用户架构

const UserSchema = new Schema<IUserSchema>(
  {
    username: {
      type: String,
      required: true,
      unique:true,
    },
  },
  {
    timestamps: true,
  }
);

我尝试了这种方法,但没有奏效。

let chat = await Chats.find({
    participants: { $elemMatch: { username: usernames } },
  })

我也试过了

let chat = await Chats.find({
    "participants.username": { $all: usernames },
  })

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    我能想到几个办法:

    选项 A:使用聚合查找参与者,然后匹配用户名
    选项 B:使用 find 从 Users 中检索用户记录,然后在 Chats 中查询匹配的 ObjectID 值
    选项 C:修改架构,使聊天也包含用户名,因此您可以直接查询它们

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 2013-11-25
      • 2019-05-16
      • 2022-10-19
      • 1970-01-01
      • 2022-01-25
      • 2014-05-13
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多