Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

87
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda