【问题标题】:Node.js/mongoose - sub-document in a array won't delete/removeNode.js/mongoose - 数组中的子文档不会删除/移除
【发布时间】:2019-01-01 08:47:47
【问题描述】:

所以这是我完成在线训练营后的第一个我自己的 node.js 项目。在我的数组中删除子文档时遇到问题。这是一些代码,我希望我能提供足够的信息来帮助我。

models:
var productSchema = new mongoose.Schema({
    name: String,
    type: String,
    location: String 
});

var clientSchema = new mongoose.Schema({
    name: String,
    address: String,
    contactinfo: String,
    products:[]    
});

这是我将产品添加到客户端的发布路线,效果很好:

//Add New Product
app.post("/clients/:id/products", middleware.isLoggedIn, function(req, res){
     Client.findById(req.params.id, function(err, client) {
            if(err){
              console.log(err);
              req.flash('error', "We cannot find the Client!!!");
              return res.redirect("/clients/" + req.params.id + "/products/new");
            }
            Product.create(req.body.product, function(err, product){
                  if(err){
                  req.flash('error', "There was an error adding the product to the user, try again");
                  } else{
                       client.products.push(product);
                       client.save();
                       req.flash('success', "You have added a New Product");
                       res.redirect('/clients/' + req.params.id +'/products/new');
                  } 
            });
     });
});

我的删除路线是我的问题孩子。它删除了产品,但我似乎根本无法将它从阵列中取出。我做了一些研究并尝试了以下方法:

client.products.find({_id:req.params.product_id}).remove()
client.products.id(req.params.product_id).remove()
client.products.pull({_id: req.params.product_id})
client.find({products:{_id: req.params.product_id}}).remove()
using client.save() right after each

我收到错误或删除客户端,
但从不从数组中删除产品。任何帮助都会很棒,或者如果有更好的方法可以做到这一点,那也很棒。在寻求帮助之前尝试了一周,因此欢迎熟练的开发人员提供反馈。

哦,这是我最后的删除路线,我想我要禁用,直到找到修复程序,这样我才能继续我的项目。

//Delete a Product
app.delete("/clients/:id/products/:product_id", middleware.isLoggedIn, function(req, res){
Product.findByIdAndRemove(req.params.product_id, function(err){
    if(err){
        console.log(err);
    } else {
        console.log("Should be deleted now!");
        Client.findById(req.params.id, function(err, client) {
            if(err){
                console.log(err);
            }
            console.log(client.products.length);
            client.find({products: {_id: req.params.product_id}}).remove();
            client.save();
            console.log(client.products.length);
            res.redirect("/clients/");
        });
    }
});

});

我用来查看是否有任何改变但从未改变的长度。

【问题讨论】:

    标签: javascript arrays node.js mongoose subdocument


    【解决方案1】:

    首先,您的方法需要objectID。试试这样,看看它是否有效:

    Product.findByIdAndRemove(ObjectId(req.params.product_id)
    

    【讨论】:

    • 感谢您提供此信息。我添加了它,但在我尝试时收到以下错误:ReferenceError: ObjectId is not defined
    • 尝试了编辑后的版本,得到了同样的信息:ReferenceError: objectID is not defined
    • 首先需要ObjectId函数 var ObjectId = require('mongodb').ObjectID;
    • 或者尝试:Product.findByIdAndRemove(ObjectId({"_id": req.params.product_id})
    • 最终使用:var ObjectId = require('mongodb').ObjectId; Product.findByIdAndRemove(ObjectId(req.params.product_id), function(err) ---- 它从产品集合/表中删除了产品,但信息仍在数组中。
    【解决方案2】:

    没关系,这里的问题似乎是我的代码。我没有在我的客户端模式中推送产品数组的引用,而是将产品信息直接推送到数组中。然后在我的一个区域的应用程序中,我正在访问 Product 集合中的数据,但在我的应用程序的另一部分,我正在通过 products 数组从客户端集合中访问相同的信息。根据我的培训(我创建的其他课程应用程序),似乎 ref 没有被删除它只是不能引用集合,因为它不再在集合中。

    感谢 Laurentiu 和 Federico 看到这里并提供一些有用的信息。对于这可能给您造成的任何头痛,我们深表歉意。

    【讨论】:

      【解决方案3】:

      查看了文档,它不会删除。它删除的是内容而不是 ID,因此它保留在 MongoDB 数据库中。

       router.delete('/inventario/:_id', function(req, res){
            Propiedades.findByIdAndDelete(req.params._id, function(err,){
               if (err){
                   res.redirect('/inventario/');
               } else {
                   res.redirect('/inventario/');
             }
          })
       });
      

      【讨论】:

        猜你喜欢
        • 2021-02-10
        • 2014-12-02
        • 2022-01-08
        • 2019-07-16
        • 1970-01-01
        • 2017-05-07
        • 1970-01-01
        • 1970-01-01
        • 2011-08-14
        相关资源
        最近更新 更多