首页 > 解决方案 > 在 Mongoose 中查询属性数组的对象

问题描述

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

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.jsmongodbmongoosemongodb-query

解决方案


我可以想到几个方法:

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


推荐阅读