How can I filter out user accounts by ._id in MongoDB?

Viewed 148

I'm creating a tinder clone, and when a user returns to use the app i want to filter out other user accounts that have been liked or disliked.

The filter function takes in the currentUser and user accounts as parameters which have been passed in by the results returned from a GET request.

If the current user has liked or disliked any other user accounts in a prior session i want those accounts filtered out so the current user cant see them again.

I've been at this for 3 weeks trying multiple different ways of looping through everything and comparing the results but i still can not get this to work properly. What I have now kinda works. But when you create a new account it get filtered out straight away without ever having the chance to be liked or disliked. The same happens when some users are liked or disliked but all and if the page is left but then retuned to any user that hasn't been liked or disliked is also removed. How can I fix this function to work properly? Or is there a better way to filter other accounts by ._id?

Get Request

router.get( "/user/match/:id", authenticateUser, asyncHandler(async (req, res, error) => {

    const currentUser = await User.findOne({ _id: req.params.id });

    if (currentUser.gender === "Male" && currentUser.sexualPreference === "Straight") {

      const users = await User.find({ gender: "Female", sexualPreference: "Straight"});

      filter(currentUser, users, req, res, error);

    };
  })
);

Filter Function

const filter = async (currentUser, users, req, res, error) => {

    try {

      if (currentUser.likes.length > 0) {
        for (const user of users) {
          for (const like of currentUser.likes) {
            if (user._id.equals(like)) {
              const index = users.indexOf(user);
              users.splice(index, 1);
              console.log(users)
            }
          }
        }
      }

    else  if (currentUser.dislikes.length > 0)  {
        console.log("dislikes")
        for (const user of users) {
          for (const like of currentUser.dislikes) {
            if (user._id.equals(like)) {
              const index = users.indexOf(user);
              users.splice(index, 1);
              console.log(users)
            }
          }
        }
      } else {
        return res.json({ users });
      }

 
      

    } catch (error) {
      console.log(error, "error");
    }
  };

currentUser

{
  matches: [],
  likes: [
    '615080280d6b7c913824bf5d',
    '61507fec0d6b7c913824bf5c',
    '61508c3d1fb5b195c62a424b',
    '6150906c0709f697acb19ae3'
  ],
  dislikes: [
    '61509280068887983227015f',
  ],
  _id: 615080750d6b7c913824bf5f,
  firstName: 'Daenerys',
  lastName: 'Targeryen',
  emailAddress: 'Daenerys@gmail.com',
  password: '$2a$10$BHZpaTKvmXp5xxDx.z1vReZ9ae922YUgn2ZDha0ou9yxe1jlXAZ6q',
  gender: 'Female',
  sexualPreference: 'Straight',
  age: 26,
  description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  path: 'uploads/1632665717723.jpg',
  __v: 0
}

Users

[
  {
    matches: [],
    likes: [],
    dislikes: [],
    _id: 61507fec0d6b7c913824bf5c,
    firstName: 'Jon',
    lastName: 'Snow',
    emailAddress: 'JonSnow@gmail.com',
    password: '$2a$10$IrnMgY6dlzftULIYNy/SWOAGalXZ30/bO78BPnaSmIT65bniQ.9pO',
    gender: 'Male',
    sexualPreference: 'Straight',
    age: 26,
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    path: 'uploads/1632665580169.jpg',
    __v: 0
  },
  {
    matches: [],
    likes: [],
    dislikes: [],
    _id: 615080280d6b7c913824bf5d,
    firstName: 'Robb',
    lastName: 'Stark',
    emailAddress: 'RobbStark@gmail.com',
    password: '$2a$10$FrBMQFj4DDbx4j9qk7iK9e.YRwSC6wd2t7QczrPEteOEniPNMqzi2',
    gender: 'Male',
    sexualPreference: 'Straight',
    age: 26,
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    path: 'uploads/1632665640435.jpg',
    __v: 0
  },
  {
    matches: [],
    likes: [],
    dislikes: [],
    _id: 61508c3d1fb5b195c62a424b,
    firstName: 'Stannis',
    lastName: 'Baratheon',
    emailAddress: 'Stannis@gmail.com',
    password: '$2a$10$8poGckIRWmuM20a97FS4HuugGwz9eocL5YfLZL46V4qi5Bk/czyQe',
    gender: 'Male',
    sexualPreference: 'Straight',
    age: 40,
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    path: 'uploads/1632668733813.jpg',
    __v: 0
  },

]


1 Answers

You are using the Users.find from mongodb to list out the users but that function actually returns a cursor and not a array of documents.

const users = await User.find({ gender: "Female", sexualPreference: "Straight"});

could become.

const users = await User.find({ gender: "Female", sexualPreference: "Straight"}).toArray();

However I recommend looking at the driver documentation for finding documents. There is probably a better way to layout your code for performance reasons. MongoDB Find Multiple Documents

Related