简体   繁体   English

如何在 mongoose 的另一个集合中找到一个集合

[英]How to find a collection inside another collection in mongoose

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.例如:我有一个名为 todoTitle 的集合,其中有一个名为 todo 的另一个集合的数组,我想找到该数组内的特定 todo 集合并将其删除。 Im trying to use findOneAndDelete but it's not working.我试图使用 findOneAndDelete 但它不起作用。 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('/');
    })
})

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.并且该错误实际上是由未定义的 ID 引起的,所以我修复了该部分,现在它可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM