Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
How to exclude more than one specific documents in mongoose?

Here, I want to exclude the document of the user who is requesting for the response as well as all those users whom the user has already send friendrequests and the users who are already friend with user, how can I achieve this?

From following code I am able to only exclude user data not other's.

try {
      
      const {id} = req.params
      const user = await userModel.findById(id)
   
      const newresponse = await userModel.find({_id:user.friendRequests}).select("_id")
      
      const response = await userModel.find({_id:{"$ne":id}}).sort({creation_date:-1}).limit(5)
      return res.json({succcess:true, response, newresponse})
    } catch (error) {
        console.log(error); 
    }

model:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  password: String,
  email: {
    type: String,
    unique: true,
  },
  birthday: Date,
  creation_date: {
    type: Date,
    default: Date.now,
  },
  gender: String,
  profile_picture: {
    type: String,
    default: "",
  },
  friends:[{
    type:mongoose.ObjectId,
    ref:"userModel"
  }],
  friendRequests:[{
    type:mongoose.ObjectId,
    ref:"userModel"
  }]

});

module.exports = mongoose.model("userModel", userSchema);


almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can concatenate friends and friendRequests arrays and pass that to the filter:

const { id } = req.params;

const user = await userModel.findById(id, 'friends friendRequests');

const excludeUsersArray = user.friends.concatenate(user.friendRequests);
   
const response = await userModel.find({ _id: { "$nin": excludeUsersArray }}).sort({ creation_date:-1 });
      
return res.json({succcess:true, response})
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!