简体   繁体   中英

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);


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM