Mongoose从嵌套数组

时间:2017-08-17 13:35:51

标签: arrays node.js mongodb mongoose

我使用的是猫鼬4.11.3。我试图从嵌套数组中删除一个对象。 这是我的架构

var VendorSchema = new Schema({
  _id: {
        type: Schema.Types.ObjectId,
        ref: "User"
    },

  services: [{    
              _id:false,
              service_category: {

                          type: Schema.Types.ObjectId,
                          ref: "ServiceCategory"
                    },
              sub_services :[{
              _id:false,
              service : {
                          type: Schema.Types.ObjectId,
                          ref: "Service"
                        },
              service_description:{
                         type: String,
                         default: null
              }
              }]                      
    }]
});

我需要删除sub_services数组中的对象。所以这就是我所做的

Vendor.update({'services.service_category': req.body.category_id}, {$pull :{'services.$.sub_services': { "service": req.body.service_id }}},function(err,obj){
            if(err){ 
                return res.json({success: false, msg: err});
            }
            else{    
                return res.json({success: true, msg:"removed" });
            }    
});

上面的代码正在执行而没有任何错误。但删除后,整个对象尚未被删除

{
    "_id": "598b28271a0b551af8fbf849",
    "services": [
        {
            "service_category": {
                "_id": "598b27f21a0b551af8fbf848",
                "category_name": "Venue"
            },
            "sub_services": [
                {
                    "service": {
                        "_id": "598b29611a0b551af8fbf84a",
                        "service": "Conference hall"
                    },
                    "service_description": "This is test description for a service"
                },
                {
                    "service": {
                        "_id": "598c66f5003db00aec18696e",
                        "service": "Auditorium"
                    },
                    "service_description": "This is test description for a service auditorium"
                },
                {
                    "service_description": null
                }
            ]
        }
    ]
}

删除后,某些属性保留为空值。但我想通过objectID(服务引用)删除整个对象。 任何人都可以帮助我

0 个答案:

没有答案