$ pull在mongoose中不起作用

时间:2018-01-18 12:06:01

标签: node.js mongodb

我正在尝试运行一个删除与任何项目相关联的标签的函数。所以这里$ pull不起作用。

"项目"模式

var itemSchema = new Schema({
  item_title: {type: String, required: true},
  discription:{type: String},
  label : {type:Array ,label_id : String },
  created_at: Date,
  updated_at: Date,
  _list: {type: Schema.Types.ObjectId, ref:'List'}
});
控制器中的

exports.deleteLabel = function (req, res){

    var label = new Label({_id:req.params.label_id});
   // label.remove();
    Item.find({},function(error,items){
        items.forEach(function(item){
            //console.log("dada");

            Item.findByIdAndUpdate(item._id,
            { $pull: {"label" : { label_id :req.params.label_id }} }
            ,function(error,result){
                if(result)console.log(result);
                else console.log("not removed");
              });
        })
  })
}

我无法理解这是什么问题。请帮我解决这个问题。 我用Google搜索了这个问题,但我还没有找到。 所以请建议任何方法来解决我的问题。我只想删除数组中的标签。

2 个答案:

答案 0 :(得分:0)

您可以尝试

exports.deleteLabel = function (req, res){

    var label = new Label({_id:req.params.label_id});
   // label.remove();
    Item.find({},function(error,items){
        items.forEach(function(item){
            //console.log("dada");

            Item.findByIdAndUpdate(item._id,
            { $pull: {"label.label_id" :req.params.label_id } }
            ,function(error,result){
                if(result)console.log(result);
                else console.log("not removed");
              });
        })
  })
}

答案 1 :(得分:0)

我找到了解决方案...... 架构及其完成的变化很少!!!!

var itemSchema = new Schema({
      item_title: {type: String, required: true},
      discription:{type: String},
      label : [label_id : String] , //Changes made here
      created_at: Date,
      updated_at: Date,
      _list: {type: Schema.Types.ObjectId, ref:'List'}
    });