简体   繁体   中英

Deleting subdocuments using mongoose returning error?

I want to delete all the sub-documents of my collection.

mongoose schema :

//productSchema
var pdtSchema = new Schema({
    "productId" : {type : String},
    "product" : {type : String},
    "item no" : {type : String},
});
    
var shopSchema = new Schema({
    "providerId" : {type : String},
    "provider" : {type : String},
    "products" : [pdtSchema]
}, { collection:"shopdetails" });
    
module.exports.Shops    = mongoose.model('Shops',shopSchema);
module.exports.Products = mongoose.model('Products',pdtSchema);

I have stored a bulk of data inside the collection and I need to delete all the products(that is the whole pdtSchema data).

code:

router.post('/delete',function (req,res) {
   var providerId = req.body.providerId;
   model.Shops.findById({"providerId" : providerId},function(err, doc) {     
     console.log(doc.products) // returns whole products here...
     doc.products.remove();
     doc.save(function(err,data){
       res.json({"msg":"deleted"});
    });
   });
 });

error:

(node:16351) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: CastError: Cast to ObjectID failed for value "[Function]" at path "_id"

Use the $unset operator which deletes the products field with the findOneAndUpdate() method. Using the traditional approach of first retrieving the document with findById() only works with a valid ObjectId , in your case you are only providing a non- ObjectId string, hence the error.

router.post('/delete',function (req,res) {
    var providerId = req.body.providerId;
    model.Shops.findOneAndUpdate(
        { "providerId": providerId },
        { "$unset": { "products": "" } },
        { "new": true }
        function(err, doc) {     
            console.log(doc) // returns modified doc here...
            res.json({"msg": "Field deleted"});
        }
    );
 });

If you want to keep the array field but remove all its elements, use $set as

router.post('/delete',function (req,res) {
    var providerId = req.body.providerId;
    model.Shops.findOneAndUpdate(
        { "providerId": providerId },
        { "$set": { "products": [] } },
        { "new": true }
        function(err, doc) {     
            console.log(doc) // returns doc with empty products here...
            res.json({"msg": "Products deleted"});
        }
    );
 });

This is because you are saving "providerId" in shopSchema as type String, even though it is a mongoose object. So, comparing a string type against a mognoose ObjectId type gives a cast error.

Instead do this,

var shopSchema = new Schema({
    "providerId" : {
        type : Schema.ObjectId
        ref : schema which they are a reference to},
        "provider" : {type : String},
        "products" : [pdtSchema]
    }, { collection:"shopdetails" });

But, I think if providerId refers to a shop Id, then it should be _id only.

model.findById() works with _id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM