【问题标题】:update by id not working in mongooseid 更新在猫鼬中不起作用
【发布时间】:2021-04-27 17:01:05
【问题描述】:

我有一个代码,其中我正在使用 mongoose 建立新连接,并且还使用模式。连接正确,我也从集合中获取属性。之后我想在我的收藏中更新,但这不起作用..我有以下代码

console.log("id : "+content._id); 
Alert.findByIdAndUpdate(content._id, {
    $set: {
        status: true
    }
}, function(error, result) {
    console.log(result);
    if (error) console.log(error);
    else {
        console.log('Alert updated');
    }
});

它显示警报已更新,但状态仍然为 false..

result for 1st console is 
id : 55096a5f91169c8e1673af20; 

and 2nd console is
Alert updated

提前致谢和问候

【问题讨论】:

  • 您能否编辑您的问题以包含您的架构和您要更新的文档?

标签: javascript node.js mongodb


【解决方案1】:

您的代码看起来很完美,id 看起来是正确的,并且您的代码没有返回任何错误,那么您是否检查过您的架构以查看它是否包含“状态”字段?

看起来您可以创建和编辑具有两边不相等架构的新文档,应用数据层。

更多信息在这里:https://github.com/Automattic/mongoose/issues/1060

【讨论】:

    【解决方案2】:

    您的代码对我来说也很合适,也许可以尝试以下方法之一?

    Alert.findOne({_id : content._id}, function(error, alert) {
        if (error) console.log(error);
        alert.status = true;
        alert.save();
    });
    

    或者

     Alert.findOneAndUpdate({_id : content._id}, {
            $set: {
                status: true
            }
        }, function(error, result) {
            console.log(result);
            if (error) console.log(error);
            else {
                console.log('Alert updated');
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 2015-11-18
      • 2018-03-03
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多