使用javascript的foreach更新mongoDB文档

时间:2017-03-28 09:35:13

标签: javascript mongodb

我在mongoDB数据库中有这个文档/对象,我会将 containerType scheduleContainerTypeEnums OVERTIME_POOL 更新为 SPARE_TIME 。 因此我尝试了这个:

db.ScheduleRecordMonthCompendiumConfirmation.find().forEach(function (doc) {    
    doc.scheduleRecordDayCompendiums.forEach(function (sch) {
       sch.confirmedScheduleIntervalContainers.forEach(function (c) {
           if (c.containerType === "OVERTIME_POOL") {
               c.containerType = "ADDITIONAL_HOURS";                       
            }
        }
    });
db.ScheduleRecordMonthCompendiumConfirmation.save(doc);
});

但没有成功。有谁知道我做错了什么?

{
"_id" : ObjectId("57f283d4e4b039723ca44d64"),
"_class" : "mydomain.MyClass",
"scheduleRecordDayCompendiums" : [  
    {
        "_id" : null,
        "institutionUserConnectionId" : "57127240e4b0f77e64ea560e",         
        "confirmedScheduleIntervalContainers" : [
            {
                "_id" : null,
                "containerType" : "OVERTIME_POOL",              
            }           
        ],
        "scheduleContainerTypeEnums" : [
            "OVERTIME_POOL"
        ],
        ...

2 个答案:

答案 0 :(得分:0)

db.ScheduleRecordMonthCompendiumConfirmation.find().forEach(function (doc) {    
    doc.scheduleRecordDayCompendiums.forEach(function (sch) {
       sch.confirmedScheduleIntervalContainers.forEach(function (c) {
           if (c.containerType === "OVERTIME_POOL") {
               c.containerType = "ADDITIONAL_HOURS";                       
            }
        }
    });

 doc.save(function(error){
  if(error){
    console.log(error)
  }
 });
});

答案 1 :(得分:0)

您的javascript结构不正确。您缺少doc.scheduleRecordDayCompendiums.forEach

的右括号
db.ScheduleRecordMonthCompendiumConfirmation.find().forEach(function (doc) {    
    doc.scheduleRecordDayCompendiums.forEach(function (sch) {
       sch.confirmedScheduleIntervalContainers.forEach(function (c) {
           if (c.containerType === "OVERTIME_POOL") {
               c.containerType = "ADDITIONAL_HOURS";                       
            }
        })
    });
 db.ScheduleRecordMonthCompendiumConfirmation.save(doc);
});