Can OR be utilized within a find operation?

I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user's page, a friend request is sent and stored in a schema called 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,
  },
});

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

Now, I need help with my code related to displaying a list of accepted friends for a user on their profile. I have an EJS page called "friends" which should show all accepted friends listed under the FriendRequest schema. For 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 });
});

The problem lies with the line where it specifies sender: req.user.id. This only displays friends whom the current user has sent requests to, but not those who have sent requests to them. Switching sender to receiver would only show friends who have sent requests to the user. How can I modify the code so that it fetches friends based on both sender and receiver being equal to req.user.id?

When I try to include both sender: req.user.id and receiver: req.user.id, no results are displayed. I am struggling to find a way to retrieve friends where either sender or receiver matches req.user.id without using || inside the find method.

This is how I want it to look:

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

I wish to achieve this without encountering any errors in my code.

Answer №1

Your syntax is incorrect. You should utilize the $or operator.

explore operators and projection

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"}
    ]
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HashId plugin for Angular

Currently, I'm attempting to integrate into my Angular project built on the latest version. After discovering this definition file: // Type definitions for Hashids.js 1.x // Project: https://github.com/ivanakimov/hashids.node.js // Definitions by: ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

The test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Implementing the Audio() Element with JavaScript

I've written the code below, but it's not working properly! When I click on the play button, nothing happens HTML: <button id="play"><img id="playicon" src="img/Polygon 1.svg"></button> JS: I have a variable named 'song0 ...

What is the best way to spin a div HTML layer?

I'm trying to modify a Div layer that looks like this: ... <style type="text/css"> <!-- #newImg { position:absolute; left:180px; top:99px; width:704px; height:387px; z-index:1; background-image:url(../Pictures/rep ...

ngModel is not taken into account when processing form data

Attempting to make use of a dynamic form in AngularJS, the code snippet below has been utilized: <dynamic-form template="formTemplate" ng-model="formData" ng-submit="processForm()"> </dynamic-form> The controller script inc ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Flatbuffers does not exist in this context

Currently, I am working on a nodeJs application that involves the use of Google Flat Buffer. After installing flatc on my MacBook Pro, I compiled the schema below: namespace MyAlcoholist; table Drink { drink_type_name: string; drink_company_name: stri ...

Laravel implementation of Bootstrap Datepicker

Incorporating Laravel bootstrap and a date picker, I have encountered an issue where the todayHighlight feature is not functioning correctly. Additionally, the container aspect is also not working as intended. <link rel="stylesheet" href="https://sta ...

Execute the identical script in NPM, but with various parameters each time

Recently, I created a nodeJS script with a parameter. Currently, using npm start allows me to pass arguments and run my script successfully. However, I'm now faced with the challenge of passing multiple arguments to npm start in order to run multipl ...

Tips for transforming a date into a time ago representation

Can someone help me with converting a date field into a "timeago" format using jquery.timeago.js? $("time.timeago").timeago(); var userSpan = document.createElement("span"); userSpan.setAttribute("class", "text-muted"); userSpan.appendChild(document.crea ...

What is the reason behind having to restart the npm server each time?

When first learning Reactjs with VSCode, there was no need to restart the server after making modifications. However, now I find that I must restart the server every time I make a change in order for those changes to be applied. ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

Utilizing AngularJS: Executing directives manually

As a newcomer to AngularJS, I am facing a challenge that requires creating a 3-step workflow: The initial step involves calling a web service that provides a list of strings like ["apple", "banana", "orange"]. Upon receiving this response, I must encap ...

Data is present in a JavaScript array, yet it is returning a value of

In my quest to create an array of User IDs for an AJAX Post Request, I encountered a strange issue. Despite successfully retrieving and displaying the User IDs individually in console.log, once I push them to the connectionData array, accessing specific in ...

arrow function implemented in a React hook for handling onClick event

From my understanding, placing an arrow function in the JSX creates a new reference of a new function each time it is triggered. For example: <p onClick={() => handleClick() /> In older versions of React with classes, we could do this: <p onCl ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

An embedded casting error occurred and failed to process the value

While utilizing Nodejs Express and Mongoose ("mongoose": "^5.3.11",), I am facing an issue when trying to add data to a collection using $push. The error message "CastError: Cast to embedded failed for value" keeps appearing, and despite exploring various ...