Mongoose.find()找不到元素

时间:2016-12-21 10:41:35

标签: javascript node.js mongodb mongoose mean-stack

我正在尝试查找并更新具有特定WEEKNUM的WEEKDATA。

架构:

{
    ageGroup:String,
    monthData: [{
        month:String,

        weekData : [{
             weekNum : String,
             theme   : String,
        }]
    }]
}

这就是我尝试这样做但它无法在文档中找到WEEKNUM而不是更新WEEKDATA,它只是创建了一个不需要的新文档:

var timeTable; // CONTAINS JSON SENT BY THE CLIENT (EXACTLY THE SAME AS SCHEMA)
TimeTable.getTimeTableModelObject().findOne(
    {
        ageGroup: timeTable.ageGroup, 
        month: timeTable.monthData.month, 
        weekNum: timeTable.monthData.weekData.weekNum
    }, function(err, foundData){
        if(err) {
            console.error("error in inserting TimeTableController.js ", err);
            return;
        }
        saveOrUpdateWeek();
    }
);

function saveOrUpdateWeek() {
    var weekData = timeTable.monthData.weekData;
    TimeTable.getTimeTableModelObject().findOneAndUpdate(
        {
            ageGroup: timeTable.ageGroup, 
            month: timeTable.monthData.month, 
            weekNum: timeTable.monthData.weekData.weekNum
        }, 
        weekData, 
        { upsert: true }, 
        function(err, foundData){
            if(err) {
                console.error("error in inserting TimeTableController.js ", err);
                return;
            }
        }
    );
}

我做错了什么,如何更新包含特定WEEKNUM的WEEKDATA?

修改

timeTable 对象包含此

{
        ageGroup:"2",
        monthData: [
            {
                month:"Jan",
                weekData : [{
                    weekNum : "1",
                    theme   : "circleTime theme weekly 2",
                }]
            },
            {
                 month:"Feb",
                 weekData : [{
                    weekNum : "2",
                    theme   : "circleTime theme weekly 2"
                 }]
            }
        ]
}

1 个答案:

答案 0 :(得分:0)

我认为您在访问对象时遇到问题,因为您使用的是使用对象数组的模式,而不仅仅是对象。尝试首先按索引访问值。例如:

var timeTable = {
    ageGroup:"2",
    monthData: [
        {
            month:"Jan",
            weekData : [{
                weekNum : "1",
                theme   : "circleTime theme weekly 2",
            }]
        },
        {
             month:"Feb",
             weekData : [{
                weekNum : "2",
                theme   : "circleTime theme weekly 2"
             }]
        }
    ]
}

console.log(data.monthData[0].weekData[0]) -> { weekNum: '1', theme: 'circleTime theme weekly 2' }

console.log(data.monthData[0].weekData[0].weekNum) - > 1