【问题标题】:how to delete object from the array of objects in mongoose如何从猫鼬的对象数组中删除对象
【发布时间】:2022-02-10 15:53:29
【问题描述】:

我有嵌套在 userSchema 中的注释我试图通过 _id 删除一个对象,但 deleteOne 正在删除整个用户对象,所以我怎样才能删除带有 _id 的对象

const keeperSchema = mongoose.Schema({
    noteName:String,
    noteContent:String,
    })

const userSchema = mongoose.Schema({
    email:String,
    password:String,
    notes:[keeperSchema]
    })

app.post("/delete",(req,res)=>{
    const id=req.body.id
    const email=req.body.email
    console.log(id)

    Keeper.deleteOne({"notes._id":id}).then(()=>{               
        Keeper.find({email:email},(err,results)=>{
            if(results){
                console.log(results)
           }
        })
    })

   })

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    你可以这样做:

      userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})
    

    您应该查询您的userModel,因为您想从存储在user 中的 keeper 数组中提取一个元素,因此您必须确定要从哪个用户删除您的注释,这就是您需要 id 的原因的用户。如果您想从所有用户中删除特定注释,只需清除您的条件,如下所示:

      userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})
    

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2021-08-23
      相关资源
      最近更新 更多