在find方法中使用OR的方法是什么?

huangapple go评论196阅读模式
英文:

Is there a way to use OR inside a find method?

问题

我正在使用Express/MongoDB开发一个Facebook克隆应用,目前正在添加好友功能。我已经实现了这样的功能:当一个用户在另一个用户的页面上点击一个按钮,上面写着“发送好友请求”,就会向对方发送好友请求,并将其存储在FriendRequest模式中。

const friendRequestSchema = new mongoose.Schema({
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  receiver: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  status: {
    type: String,
    enum: ["pending", "accepted", "rejected"],
    default: "pending",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

用户会收到通知,他们可以选择接受或拒绝请求。如果他们接受了好友请求,状态将从“pending”更改为“accepted”。

以下是我的代码:

我有一个friends ejs 页面,我试图映射用户在其分配的FriendRequest模式中拥有的所有“accepted”好友。我计划使用此页面来显示用户的所有好友列表。例如:/:user/friends

router.get("/:user/friends", async function (req, res) {
  const user = req.user.username;

  const friends = await FriendRequest.find({
    sender: req.user.id, // 这里有问题
    status: "accepted",
  })
    .populate("sender")
    .populate("receiver")
    .exec();
  res.render("friends", { user, friends });
});

问题出在sender: req.user.id这一行。当我这样写时,它只显示我个人发送好友请求的好友列表,不显示任何向我发送好友请求的好友。反之亦然。如果我将sender更改为receiver,它将只显示向我发送好友请求的好友。

下面是使用console.log时一个已接受好友的示例。每个好友都分配了“sender”或“receiver”。

_id: new ObjectId("6471d4a3a705acadf8af8923"),
   sender: {
     friends: [],
     _id: new ObjectId("6454407483df47caef5004e2"),
     username: 'Dagger',
     createdAt: 2023-05-04T23:32:04.128Z,
     __v: 0
},

当我将sender: req.user.idreceiver: req.user.id同时放入代码中时,什么都不显示。我一直在尝试找到一种方法,使得如果senderreceiver等于req.user.id,它将显示好友的用户名,但我一直在努力找出方法,因为我不能在find方法中使用||

我希望我的代码看起来像这样:

const friends = await FriendRequest.find({
    sender || receiver: req.user.id,
    status: "accepted",
})

但以一种不会导致错误的方式。

英文:

I'm working on a Facebook clone using Express/MongoDB and I'm working on adding friends. I have it so when a user clicks a button on another users page that says "Send Friend Request" it sends a friend request to them and is stored inside a FriendRequest schema.

const friendRequestSchema = new mongoose.Schema({
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  receiver: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  status: {
    type: String,
    enum: ["pending", "accepted", "rejected"],
    default: "pending",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

The user is notified and they can either accept or deny the request. If they accept the friend request, the status changes from pending to accepted.

Here's where my code comes in.

I have a friends ejs page and I'm trying to map all accepted friends that a user has in their assigned FriendRequest schema. I'm planning on using this page to show a list of all a users friends. Example: /:user/friends.

router.get("/:user/friends", async function (req, res) {
  const user = req.user.username;

  const friends = await FriendRequest.find({
    sender: req.user.id, // my issue
    status: "accepted",
  })
    .populate("sender")
    .populate("receiver")
    .exec();
  res.render("friends", { user, friends });
});

There is my code. The problem has to do where it says sender: req.user.id. When I have it like that, it only shows a list of friends that I personally have sent friend requests to, and doesn't show any friends that have sent friend requests to me. And vice versa. If I change sender to receiver it will only show friends that have sent me friend requests.

Here's an example of an accepted friend when I use console.log. Each one is assigned either sender or receiver.

_id: new ObjectId("6471d4a3a705acadf8af8923"),
   sender: {
     friends: [],
     _id: new ObjectId("6454407483df47caef5004e2"),
     username: 'Dagger',
     createdAt: 2023-05-04T23:32:04.128Z,
     __v: 0
},

When I put both sender: req.user.id and receiver: req.user.id inside the code, nothing shows up at all. I've been trying to find a way to make it so if sender OR receiver is equal to req.user.id that it will show the username of the friend but I'm struggling to figure out a way because I can't use || inside the find method.

I want my code to look like this

const friends = await FriendRequest.find({
    sender || receiver: req.user.id,
    status: "accepted",
})

but in a way that won't give me errors.

答案1

得分: 4

你的语法有误。你需要使用$or运算符。

参考运算符和投影

    $or: [
         {sender: req.user.id},
         {receiver: req.user.id}
    ],
    status: "accepted"
})```

或

```const friends = await FriendRequest.find({
    $and: [
         {$or: [
              {sender: req.user.id},
              {receiver: req.user.id}
          ]},
          {status: "accepted"}
    ]
})```

<details>
<summary>英文:</summary>

Your syntax is wrong. You need to use `$or` operator.

[refer operators and projection](https://www.mongodb.com/docs/manual/reference/operator/query/)

const friends = await FriendRequest.find({
$or: [
{sender: req.user.id},
{receiver: req.user.id}
],
status: "accepted"
})


OR 

const friends = await FriendRequest.find({
$and: [
{$or: [
{sender: req.user.id},
{receiver: req.user.id}
]},
{status: "accepted"}
]
})


</details>



huangapple
  • 本文由 发表于 2023年5月29日 16:03:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定