Remove object from nested array failed

Viewed 40

A team has many projects. Im trying to delete a project, and so I need to delete it in marcsEquipa[] too.

TEAM SCHEMA

const EquipaSchema = new mongoose.Schema({

    trab1: { 
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Trab'
    },
    trab2: { 
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Trab'
    },
    trab3: { 
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Trab'
    },
    teamName: {
        type: String,
        required: true
    },
    marcsEquipa: [{
        type: Schema.Types.ObjectId,
        ref: 'Marcacao'
    }]
},
{collection: 'Equipas'})

Function Delete Project

exports.deleteMarc = async (req,res) => {

    console.log("Deleting Project..");
    console.log(req.params._id);
    console.log(req.params.equipa);
    try{
    console.log("1");
    const equipa = await 
    Equipas.updateOne({ _id: req.params.equipa}, { $pull: { marcsEquipa: { _id: req.params._id}}}, { multi: true });
    equipa.save();

    console.log("1");

    //await Marcacao.deleteOne({_id: req.params._id});
    res.status(200).json();
        
    console.log("1");

}catch(err) {
    res.status(400).json({message: err});
}

}

I've tried this and it manages to delete the Project but it doesn't delete it within the array of Projects in Team. Can anyone help?

1 Answers

You are trying to pull the item with _id property, but the items are just the string representation of ObjectId. So, instead of this:

{ $pull: { marcsEquipa: { _id: req.params._id }}}

do this:

{ $pull: { marcsEquipa: req.params._id }}
Related