繁体   English   中英

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

[英]How to exclude more than one specific documents in mongoose?

在这里,我想排除正在请求响应的用户的文档以及用户已经发送了好友请求的所有用户以及已经与用户成为好友的用户,我该如何实现呢?

从下面的代码中,我只能排除用户数据而不是其他数据。

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


您可以连接friends和朋友friendRequests并将其传递给过滤器:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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