gpt4 book ai didi

javascript - 根据类别更新对象类型的mongodb字段

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:23 24 4
gpt4 key购买 nike

我的 MongoDB 集合中有以下文档。

{
"_id" : ObjectId("5ce34ac6a2f25b2448b9b3a3"),
"userId" : ObjectId("5ce34ac6a2f25b2448b9b3a0"),
"providers" : [
"1689736266",
"1598763690",
"1528069614",
"1831364272",
"1548463045",
"1245301159",
"1386616399",
"1790775971",
"1629462130",
"1992169783"
],
"countByType" : {
"doctors" : 0,
"labs" : 0,
"hospitals" : 0,
"imagingCenters" : 0
}
}

类别包括医生、实验室、医院和成像中心。问题是,对于某个特定用户来说,他没有医院类别,而另一个用户可能有。所以我需要根据用户类别更新 MongoDB 中的 countByType 字段。如果用户不包含医生类别,则不需要在MongoDB中更新。当我尝试更新计数时,不存在的类别将变为空值。

请参阅更新查询:

let updateProviderId = await userProviderCollection.update(
regUserId, {
$set: {
providers: providernpiId,
countByType: {
"doctors" : counts.doctor,
"labs" : counts.lab,
"hospitals" : counts.hospital,
"imagingCenters" : counts.imagingcenter
}
}

});

现在我得到的输出为

"countByType" : {
"doctors" : 6,
"labs" : null,
"hospitals" : null,
"imagingCenters" : null
}

预期输出:

"countByType" : {
"doctors" : 6,
"labs" : 1,
"hospitals" : 0,
"imagingCenters" : 0
}

如果用户类别包含医生和实验室。

最佳答案

您只需要预先检查 counts 对象中的键是否存在,如果您想更新 mongodb 中的嵌套对象键,则需要使用点运算符指定完整的键路径,如下所示:

let setObj = {
providers: providernpiId
};
let {
doctor,
lab,
hospital,
imagingcenter
} = counts;
doctor && (setObj["countByType.doctor"] = doctor);
lab && (setObj["countByType.lab"] = lab);
hospital && (setObj["countByType.hospital"] = hospital);
imagingcenter && (setObj["countByType.imagingcenter"] = imagingcenter);
let updateProviderId = await userProviderCollection.update(
regUserId, {
$set: setObj
});

关于javascript - 根据类别更新对象类型的mongodb字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56291135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com