How to find a collection inside another collection in mongoose

Viewed 113

Im trying to delete a specific document that is inside a collection that is also inside another collection. For example: I have a collection called todoTitle and inside it has an array of another collection called todo, I want to find that specific todo collection that is inside the array and delete it. Im trying to use findOneAndDelete but it's not working. here is the code:

const TodoSchema = new mongoose.Schema({
    name:  String,
})
const todo = mongoose.model('todo', TodoSchema)

const TodoTitleSchema = new mongoose.Schema({
    title: String,
    content: [TodoSchema],
})
const todoTitle = mongoose.model('todoTitle', TodoTitleSchema)

app.post('/removeTodo',(req,res)=>{
    let todoID = req.body.removeTodo;
    todoTitle.findOneAndDelete({content:[{_id: todoID}]}, (err, foundtodo)=>{
        console.log(foundtodo);
        if(err){
            console.log(err)
        }
        res.redirect('/');
    })
})
1 Answers

Hello so I finally figured it out, I had to write this code:

todoTitle.findOneAndUpdate({_id: listID}, {$pull: {content: {_id: todoID}}}, (err, foundtodo)=>{
        if(err){
            console.log(err)
        }
    })

and the error was actually caused by the ID being undefined so I fixed that part up and now it works.

Related