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);
CodePudding user response:
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})