如何根据两个字段从mongoose模型中获得不同的值?

如何根据两个字段从mongoose模型中获得不同的值?,mongoose,Mongoose,我对问题感到震惊,在这个问题中,我有猫鼬模型的信息如下: const MessageSchema = new mongoose.Schema( { by: { type: String, required: true, }, to: { type: String, required: true, }, body: { type: String, required: true,

我对问题感到震惊,在这个问题中,我有猫鼬模型的信息如下:

const MessageSchema = new mongoose.Schema(
  {
    by: {
      type: String,
      required: true,
    },
    to: {
      type: String,
      required: true,
    },
    body: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);
我想得到这个模型中的所有唯一用户,任何特定的用户都可以向这些用户发送消息,也可以接收消息

const users = await Message.find({
   $or: [
     { by: req.user.userName },
     { to: req.user.userName },
   ],
 });
这是我的查询,它给了我结果,但它们并不明显。 我可以用

.distinct()
猫鼬的方法,但如何在“to”和“by”字段上使用它


如果您也能给出如何排序的解决方案,那就太好了,因为我们不能在mongoose中将sort()方法与distinct()一起使用。

您尝试过聚合吗?是的,我尝试过,但在这里没有用,因为它要求您同时检查两个字段。