mongodb 按ID更新不更改Mongoose中的字段

nwlls2ji  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(139)

我有一段代码,我用Mongoose和schema建立了一个新的连接。连接建立得很好,我也从集合中获取了属性。之后我想在我的集合中更新,但这不起作用。我有以下代码

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

它显示警报已更新,但状态仍为假。

result for 1st console is 
id : 55096a5f91169c8e1673af20; 

and 2nd console is
Alert updated
hxzsmxv2

hxzsmxv21#

您的代码看起来很完美,id看起来很正确,并且代码没有返回任何错误,那么您是否检查过您的模式以查看它是否包含“status”字段?
看起来你可以用一个两边不相等的架构来创建和编辑新文档,应用一个数据层。
更多信息:https://github.com/Automattic/mongoose/issues/1060

nbysray5

nbysray52#

你的代码看起来也对我来说,也许尝试以下之一?

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

相关问题