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

Mongoose中updateMany与updateOne不生效,应使用$ne还是$nin实现数组条件插入?

问题解决方案

操作符选择说明

  • 你当前需要判断单值是否不存在于数组中的场景,使用$ne即可。$nin主要用于匹配字段值不在多个指定候选值列表的场景,你现有写法中$nin: [req.user._id]逻辑上虽然可以运行,但属于冗余用法,不符合操作符的设计定位。
  • 你现有代码没有实现预期效果,大概率不是操作符选择的问题,更常见的原因是类型不匹配:req.user._id通常为字符串类型,而MongoDB中存储的_id为ObjectId类型,类型不一致会导致查询匹配失败。

更优实现方案

不需要在查询条件中判断值是否存在,直接使用MongoDB原生的$addToSet更新操作符即可,它天生具备「仅当值不存在于数组时才插入」的特性,属于原子操作,还能避免并发场景下的重复插入问题,代码更简洁可靠。

修改后的代码如下:

const mongoose = require('mongoose');

router.post('/deleteChat', async (req, res) => {
    if(!req.isAuthenticated()) return res.status(400).json({message: "用户未登录"});
    
    const {currentConversation} = req.body;
    // 统一转换为ObjectId类型,避免类型不匹配导致的查询失败
    const userId = mongoose.Types.ObjectId(req.user._id);
    const conversationId = mongoose.Types.ObjectId(currentConversation._id);

    try {
        await Messages.updateMany(
            { about: conversationId },
            { $addToSet: { who_delete: userId } }
        );
        await Conversation.updateOne(
            { _id: conversationId },
            { $addToSet: { status: userId } }
        );
        return res.json()
    } catch (error) {
        // 建议保留错误日志打印,方便后续排查问题
        console.error('更新失败:', error);
        return res.status(500).json({message: "发生未知错误"})
    }
});

原有逻辑兼容写法

如果你需要保留原有查询侧判断的写法,仅修改操作符和类型即可:

await Messages.updateMany(
    { 
        about: conversationId, 
        who_delete: { $ne: userId } 
    },
    { $push: { who_delete: userId } }
);

内容的提问来源于stack exchange,提问作者Azizjon Nuryagdyyev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:39:03