【问题标题】:Delete item from nested array in Schema using moongoose使用猫鼬从模式中的嵌套数组中删除项目
【发布时间】:2017-12-23 02:55:38
【问题描述】:

我需要有关从嵌套数组中删除 this 项目的帮助。我尝试使用$http.delete,但是这种方法从数据库中删除了整个 ObjectID,第二个问题是我无法将单击“删除”按钮与后端代码连接起来。

我的代码:

var product = new Schema({
  title: String,
  price: String,
  description: [ObjectID]
});

索引.html

<form name="editProduct.descriptionForm" ng-submit="editProduct.updateDescription(newDescription, editProduct.descriptionForm.description.$valid)" novalidate>
  <div ng-class="{ 'has-success':(editProduct.descriptionForm.description.$valid && !editProduct.descriptionForm.description.$pristine), 'has-error':(!editProduct.descriptionForm.description.$valid && !editProduct.descriptionForm.description.$pristine) || (!descriptionForm.description.$valid && descriptionForm.$submitted) }">

    <div class="entry input-group" ng-repeat="item in newDescription track by $index">
      <strong><input ng-disabled="editProduct.disabled" class="form-control" type="text" name="description" ng-model="newDescription[$index]" required></strong>
      <span class="input-group-btn">
        <a ng-click="editProduct.deleteDescription(item);" class="btn btn-remove btn-danger">
            <span class="glyphicon glyphicon-remove"></span>
        </a>
      </span>
    </div>
  </div>
  <br>
  <button ng-disabled="editProduct.disabled" class="btn btn-primary" type="submit">Save</button>
</form>

routes.js

router.put('/editProduct', function(req, res){
  var editProduct = req.body._id;
  var options = { multi: true };
  Product.findOneAndUpdate({ _id: editProduct }, { $pull: { description: req.params.description }}, options, function(err, product){
    if(err) throw err;
    if(!product){
      res.json({ success: false, message: 'Product no found' });
    } else {
      product.update(function(err){
        if(err){
          console.log(err);
        } else {
          res.json({ success: true, message: 'Description removed!'})
        }
      });
    };
  });   
});    

我也尝试了以下方法:

Product.findOne({'_id' : product.id}, function(err, me){
  for(var i=0; i<=me.description.length; i++){
    if (String(me.description[i])==String(uid)){
      me.description.remove(uid);
      me.save();                         
    }
  }    
});

我认为,最大的问题是我不知道如何将这个功能连接到按钮。

【问题讨论】:

  • 我会把你的问题分成2-3个小问题。
  • 它看起来很糟糕,但我认为这个问题很短,也许有人反对从数组中删除项目点击

标签: javascript node.js mongoose


【解决方案1】:

请在 Mongoose 更新查询之前尝试 console.log(req.params.description) 并检查输出是否确实是有效的 ObjectId。

如果控制台输出未显示有效的 uid,则问题出在 Angular 代码中。很可能在editProduct.deleteDescription(item) 函数中。通过传递正确的描述 ID 作为参数来检查您是否正在发出 Http 请求。这可能类似于 item.descriptionId 或 item.id。彻底调试。

【讨论】:

  • 一切似乎都很好,但我收到消息“找不到产品”
猜你喜欢
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 2017-01-16
  • 2021-08-23
  • 2020-08-01
  • 2019-03-22
  • 1970-01-01
  • 2015-09-21
相关资源
最近更新 更多