简体   繁体   English

从数组中删除一个元素,即在 Object 内

[英]Deleting an element from an Array, that is inside an Object

In my To-Do app, when a logged-in User completes a task, I would like to clear it from the MongoDB database.在我的待办事项应用程序中,当登录用户完成一项任务时,我想将其从 MongoDB 数据库中清除。

Here is the code for my Schema.这是我的架构的代码。

const user = new mongoose.Schema({
    username : String,
    password : String,
    task : [{
        text : String,
        day : String,
        reminder : Boolean,
    ]}
 })
    

For example , if Daryl completed text: "Gym" & day: "Feb 4th 5.30pm" , I would like to only remove task[0] from Daryl's task Array.例如,如果 Daryl 完成了text: "Gym" & day: "Feb 4th 5.30pm" ,我只想从 Daryl 的任务数组中删除任务 [0]。

Here is my attempt at doing so using Mongoose,这是我尝试使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 这样做,

app.delete("/tasks", (req,res) => {
    User.findOne( {_id : req.user.id}).then((target) => {
        target.task.remove({text : req.body.text, day : req.body.day})
        })
}) 
  1. User.findOne({_id: req.user.id}) to only target the person that logged in User.findOne({_id: req.user.id}) 只针对登录的人
  2. Once targeted, access task array using.task定位后,使用.task 访问任务数组
  3. and use.remove along with filters, to remove that entry from the array和 use.remove 连同过滤器,从数组中删除该条目

I have console.logged() all the variables and it tallies with the data fields, however the entry is not being removed.我有 console.logged() 所有变量,它与数据字段相符,但是条目没有被删除。 What am I doing wrong?我究竟做错了什么?

I managed to solve my problem, hopefully this helps someone else我设法解决了我的问题,希望这对其他人有帮助

app.delete("/tasks", (req, res) => {
    User.findByIdAndUpdate(req.user.id, {$pull: {"task": {text: req.body.text}}}, {safe: true, upsert: true},
        function (err, node) {
        // console.log here for debugging, if you want
        })
})

This successfully erases items based on这成功地删除了基于

  1. req.user.id请求.user.id
  2. "task": {//whatever your stricter conditions are} "task": {//无论你的条件更严格}

I still don't understand why my earlier attempts failed, but at least this one works.我仍然不明白为什么我之前的尝试失败了,但至少这个有效。

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

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