MongoDB / Mongoose $ pull(删除)子文档无法正常工作

时间:2016-01-19 19:06:34

标签: node.js mongodb mongoose

把头撞到键盘上。

只需删除子文档。下面的示例在OnCommands中只有一个项目,但那里可能有很多项目。我试过find,findbyid,updatebyId,pull,一个接一个的东西。尝试通过subid的_id和通用searchinMost简单运行而不做任何错误。

如果你能告诉我我做错了什么,我会非常高兴,这是我的代码的最后一部分是行不通的。

示例数据:

> db.EntryPoints.find({_id: ObjectId("569e4fabf1e4464495ebf652")}).pretty()
{
        "__v" : 0,
        "_id" : ObjectId("569e4fabf1e4464495ebf652"),
        "name" : "bbbb",
        "offCommands" : [ ],
        "onCommands" : [
                {
                        "data" : "11111",
                        "operation" : "on",
                        "command" : "ISY-HTTPGet",
                        "_id" : ObjectId("569e4faff1e4464495ebf653")
                }
        ]

型号:

var mongoose = require('mongoose');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var onCommandsSchema = new Schema({
    command: String
    ,operation: String
    ,data: String
})

var offCommandsSchema = new Schema({
    command: String
    ,operation: String
    ,data: String
})

mongoose.model('onCommands', onCommandsSchema);
mongoose.model('offCommands', offCommandsSchema);

// create a schema
var EntryPointsSchema = new Schema({
    name: String
    ,onCommands: [onCommandsSchema]
    ,offCommands: [offCommandsSchema]
    ,description: String
}, { collection: 'EntryPoints' });
mongoose.model('EntryPoints', EntryPointsSchema);


var EntryPoints = mongoose.model('EntryPoints');

module.exports = EntryPoints;

节点邮政编码:

router.post('/webservices/removeCommand', function (req, res) {
    var EntryPoints = require('../data_models/automate_entrypoints.js');

    EntryPoints.update(
        { _id: ObjectId(req.body._id) }
        , {
            $pull: {
                onCommands: { id_: req.body._id }
            }
        }
        , function (err, ouput) { console.log("data:", numAffected) }
    );  

});

1 个答案:

答案 0 :(得分:5)

由于您的更新的查询部分,您的代码无法正常工作:您希望匹配嵌入文档_id,而不是主文档。所以把它改成

var EntryPoints = require('../data_models/automate_entrypoints.js');

EntryPoints.update(
    { "onCommands._id": req.body._id }, 
    {
        "$pull": {
            "onCommands": { "_id": req.body._id }
        }
    }, 
    function (err, numAffected) { console.log("data:", numAffected) }
);