我目前正在消息应用程序中创建收件箱。为此,我想提取我存储在消息架构中的所有唯一用户 ObjectID,以查看用户正在进行的所有唯一对话。问题在于 ObjectID 存储在两个单独的字段中:“to”和“from”。有什么方法可以从两个字段中获取不同的值吗? (即如果 userA 出现在 to 和 from 中,则仅提取一次)
目前我尝试使用 $setUnion 和 $addToSet 但没有成功。
我的消息架构如下
const MessageSchema = new Schema(
{
message: { type: String, required: true, maxLength: 128 },
image: { type: String },
from: { type: Schema.Types.ObjectId, required: true, ref: "User" },
to: [
{
type: Schema.Types.ObjectId,
required: true,
refPath: "docModel",
},
],
docModel: { type: String, required: true, enum: ["Group", "User"] },
},
{ timestamps: true },
);
以下是一些示例文档:
[
{
"_id": "671175112a0bcfdb66f833fc",
"message": "hi",
"from": "6706c5576692b95bb39dabae",
"to": [
"6708368712a817cd73810b5e"
],
"docModel": "User",
"createdAt": "2024-10-17T20:35:29.164Z",
"updatedAt": "2024-10-17T20:35:29.164Z",
"__v": 0
},
{
"_id": "6711755e2a0bcfdb66f83406",
"message": "bye",
"from": "671175392a0bcfdb66f83401",
"to": [
"6706c5576692b95bb39dabae"
],
"docModel": "User",
"createdAt": "2024-10-17T20:36:46.259Z",
"updatedAt": "2024-10-17T20:36:46.259Z",
"__v": 0
},
{
"_id": "671181f7c2db995b7ef3f976",
"message": "1",
"from": "6706c5576692b95bb39dabae",
"to": [
"671175392a0bcfdb66f83401"
],
"docModel": "User",
"createdAt": "2024-10-17T21:30:31.032Z",
"updatedAt": "2024-10-17T21:30:31.032Z",
"__v": 0
}
]
在上面的示例中,我希望获得的结果是一个数组:
[6706c5576692b95bb39dabae, 671175392a0bcfdb66f83401, 6708368712a817cd73810b5e]
它是出现在 from 或 to 中的唯一值(如果它们同时出现在 from 或 to 中,则它们只会被推送到数组一次)
我查询MongoDB的代码如下。我尝试查询所有用户 ID 出现在“to”或“from”中的文档。然后我尝试获取两个字段组合的唯一值,但这不起作用。
一旦提取了所有唯一 ID 以得出唯一对话的最终列表,我计划删除请求用户的用户 ID。
const uniqueUsers = await Message.aggregate([
{
$match: {
$or: [
{
from: new mongoose.Types.ObjectId(`${req.user.id}`),
},
{
to: {
$in: [
new mongoose.Types.ObjectId(`${req.user.id}`),
],
},
},
],
},
},
{
$group: {
_id: null,
unique: { $setUnion: ["$from", "$to"] },
},
},
]);