node.js - 在 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 },
})
解决方案
我可以想到几个方法:
选项 A:使用聚合查找参与者,然后匹配用户名
选项 B:使用 find 从用户中检索用户记录,然后查询聊天以获取匹配的 ObjectID 值
选项 C:修改架构,使聊天也包含用户名,这样您可以直接查询
推荐阅读
- swiftui - 渲染后swiftui页面空白
- javascript - 使用 axios 取消请求时是否会出现延迟
- typescript - Vue Prop 未定义,和/或不能在 v-for 上使用。使用打字稿和装饰器
- java - Java读写高分
- python - Sympy - Lambdify - 虚拟变量的挖掘名称
- git - 名为“master”的分支是特殊的吗?
- nativescript - nativescript-custom-local-notifications 插件给出:无法读取未定义错误的属性 \'Builder\'
- assembly - 在 MIPS 中访问 .space 元素(降序)
- spring - Spring Boot JPA OneToMany 返回 Null
- sql - SQL, max(), 分组依据