You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中排除多个特定文档:自身、好友及已请求用户

解决Mongoose查询中排除三类用户的问题

你需要在查询中排除三类用户:当前用户自身、已发送好友请求的用户、已成为好友的用户。可以通过Mongoose的$nin操作符一次性完成排除,以下是修改后的实现代码:

修改后的完整代码

try {
  const { id } = req.params;
  const user = await userModel.findById(id);

  // 合并需要排除的用户ID数组:自身ID + 好友ID + 已发送请求的用户ID
  const excludedUserIds = [id, ...user.friends, ...user.friendRequests];

  // 查询时排除上述所有ID的用户
  const response = await userModel.find({
    _id: { $nin: excludedUserIds }
  }).sort({ creation_date: -1 }).limit(5);

  // 保留你原有的newresponse查询(如果不需要可以移除)
  const newresponse = await userModel.find({ _id: user.friendRequests }).select("_id");

  return res.json({ success: true, response, newresponse });
} catch (error) {
  console.log(error);
}

关键逻辑说明

  • 使用$nin操作符:该操作符会匹配不在指定数组内的文档,正好满足我们排除多类用户的需求。
  • 合并排除ID数组:将当前用户ID、friends数组中的好友ID、friendRequests数组中已发送请求的用户ID合并成一个数组,一次性传入$nin。
  • 保持原有排序和分页:保留你原有的sort和limit逻辑,确保返回最新的5条符合条件的用户数据。

数据模型说明(供参考)

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

内容的提问来源于stack exchange,提问作者Dhiran Sapkota

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:10:48