Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda