簡體   English   中英

使用 DELETE Rest api 從 Mongodb 中刪除數組 object

[英]Using DELETE Rest api to remove array object from Mongodb

我使用的是 Node.js、express、mongodb 和 mongoose。我有兩個文件:favorite 和 favorite-route。

架構中的“收藏夾”在其數組中有多個對象。 給定 mongodb 分配的 _id,我想創建一個刪除方法來 gremove 數組中指定的 object。

這是我最喜歡的架構:

    userID:{
        //type: String,
        
        type: mongoose.Schema.Types.ObjectId,
        ref: "user",
        required: true,
        unique: true
    },
    favorites:[{
        
        publication: {
            type:mongoose.Schema.Types.ObjectId,
            ref: "Pet"
        },

        id: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        }
    }]   
})
favoritesSchema.statics.deleteFavorite = async (favID)=>{
    return await Favorite.findOneAndUpdate({favID})
}

這是我在最喜歡的路線文件中的刪除方法:

router.delete('/:favID', async (req,res)=>{

    let doc = await Favorite.deleteFavorite(req.params.favID)

    if(doc){
        doc.splice(req.params.favID);
        res.send(doc)
        return;
    }

    res.status(404).send({error: "no se encontró esa publicación"})
})

最后,這是我的 http:

DELETE {{host}}/api/favorites/626eddd14762eb4ae4c77f9e

當我測試這個時,它給了我錯誤: TypeError: doc.splice is not a function

我將不勝感激任何提示和見解。 我花了一段時間尋找答案,但大多數人建議使用 $pull,我不確定如何在 delete 方法中實現它。

謝謝:)

你應該做。

    Favorite.updateOne(
      { userID: user._id }, // this is the query to find the desired favourite list
      { $pull: { favorites: { id : req.params.favID }} }, // this removes  
     
    );


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM