Node + Mongodb。 $拉不工作?

时间:2016-03-31 00:43:50

标签: node.js mongodb

我正在使用Node.js和MongoDB,我正在尝试设置DELETE路由。在负责处理删除的函数中,我正在使用Mongo的“$ pull”运算符。我现在看了几个例子,我不知道我做错了什么。

以下是如何设置数据库文档的示例

{
"_id": {
    "$oid": "123abc"
},
"sleepData": [
    {
        "date": "03/28/2016",
        "hour": "11",
        "minute": "11",
        "meridiem": "PM",
        "feeling": "7"
    },
    {
        "date": "03/29/2016",
        "hour": "3",
        "minute": "41",
        "meridiem": "PM",
        "feeling": "1"
    },
    {
        "date": "03/30/2016",
        "hour": "1",
        "minute": "29",
        "meridiem": "AM",
        "feeling": "5"
    },
    {
        "date": "03/30/2016",
        "hour": "1",
        "minute": "38",
        "meridiem": "AM",
        "feeling": "4"
    },
  ]
}

*注意几乎重复的数据,因此我的$ pull查询是如此具体的原因。

这是我的路线功能

module.exports.DELETE = function(req, res) {
var sleepDataToDelete = {
    date: req.query.date,
    hour: req.query.hour,
    minute: req.query.minute,
    meridiem: req.query.meridiem,
    feeling: req.query.feeling
};

// next code block is what this console prints out
console.log("Deleting req.query:\n", sleepDataToDelete);

var sleepObjectId = req.query.sleepObjectId;
var sleepDataCollection = db.get().collection('sleepData');
sleepDataCollection.update(
    {
        _id: sleepObjectId
    },
    {
        $pull: {
            sleepData: {
                date: sleepDataToDelete.date,
                hour: sleepDataToDelete.hour,
                minute: sleepDataToDelete.minute,
                meridiem: sleepDataToDelete.meridiem,
                feeling: sleepDataToDelete.feeling
            }
        }
    },
    function(err, result) {
        if(err) {
            console.log("err", err);
            return res.status(400).end();
        } else {
            console.log("Count: ", result.result.n);
            console.log("Deleted! :) ");
            return res.status(200).end();
        }
    }
);

};

这就是console.log(“Deleting req.query:\ n”,sleepDataToDelete); print out,也匹配sleepData数组中的第三个索引。

Deleting req.query:
{ 
  date: '03/30/2016',
  hour: '1',
  minute: '29',
  meridiem: 'AM',
  feeling: '5'
}

我甚至尝试将json字段名称放在双引号/单引号中,但这也不起作用。修改的对象数量为0.我还尝试将“$ pull {...}”查询缩减为“date”而不是“date”,“hour”,“minute”,“meridiem”和“感觉。”这仍会导致print语句中有0个修改过的项目。

1 个答案:

答案 0 :(得分:0)

正如@BlakesSeven指出的那样,我没有在查询中传入ObjectId。所以,归功于他。不用说,这解决了我的问题。