如何在mongoose中排除多个特定文档?

bxgwgixi  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(136)

这里,我想排除正在请求响应的用户的文档,以及该用户已经发送好友请求的所有用户和已经与该用户成为好友的用户,我如何才能做到这一点?
从下面的代码中,我只能排除用户数据,而不能排除其他数据。

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

型号:

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

2vuwiymt1#

您可以连接friendsfriendRequests数组,并将其传递给筛选器:

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

相关问题