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

如何在Mongoose中排除指定用户的文档

在Mongoose中排除特定用户文档的实现方法

要排除指定userId的文档,直接在find()的查询条件里使用MongoDB的$ne(不等于)操作符即可。

你的代码里req.params.id就是要排除的用户ID,修改查询条件如下:

async peopleyoumayknow(req, res) {
    const {id} = req.params
    // 排除_id等于当前id的用户文档
    const response = await userModel.find({ _id: { $ne: id } })
        .sort({creation_date:-1})
        .limit(12)
    return res.send(response)
}

注意事项:

  • $ne操作符用于筛选出所有_id不等于目标值的文档,刚好满足你排除特定用户的需求
  • Mongoose会自动将字符串类型的id转换为MongoDB所需的ObjectId类型,无需手动处理类型转换

内容的提问来源于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.19 01:35:26