Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
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"
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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"});
        }
    );
 });
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!