简体   繁体   中英

How to delete an object from an array situated in another object in Javascript?

I am working in a Node, mongoose, express app and I want to delete an object from an array that is inside and object. The structure would be like this:

const oldSection = {
  _id: '62d3f1d221aa21a03fe3bc21',
  name: 'Section',
  learners: [{
    _id: '62d6f9b64add603ff0d53257',
    name: 'Test 1'
  },
  {
    _id: '62d6fa5bfbdbbebc83a3923a',
    name: 'Test 2'
  }]
}

So, for this, I used following code:

personRouter.put('/:id', userExtractor, async (request, response, next) => {
  const { id } = request.params
  const person = request.body

  const isScouter = person.isScouter
  const sectionId = person.section
  const section = await Section.findById(sectionId)
  const oldPerson = await Person.findById(id)
  const oldSectionId = oldPerson.section
  const oldSection = await Section.findById(oldSectionId)

  console.log(`Old Person: ${oldPerson}`)
  console.log(`Old Section: ${oldSection}`)

  const newPersonInfo = {
    name: person.name,
    surname: person.surname,
    credential: person.credential,
    isScouter,
    section: sectionId
  }

  try {
    const savedPerson = await Person.findByIdAndUpdate(id, newPersonInfo, { new: true })

    if (isScouter === true) {
      oldSection.scouters.filter(person => person.id !== id)
      section.scouters = section.scouters.concat(savedPerson._id)
      await oldSection.save()
      await section.save()
    } else if (isScouter === false) {
      console.log(`Test1: ${oldSection.learners}`)
      console.log(`Test2: ${id}`)
      oldSection.learners = oldSection.learners.filter(person => person.id !== id)
      console.log(`Test3: ${oldSection.learners.filter(person => person.id !== id)}`)
      console.log(`Test4: ${oldSection.learners}`)
      section.learners = section.learners.concat(savedPerson._id)
      await oldSection.save()
      await section.save()
    } else {
      console.log('To be done')
    }

    Person.findByIdAndUpdate(id, newPersonInfo, { new: true }).then(result => {
      response.json(result)
    }).catch(error => next(error))
  } catch (error) {
    next(error)
  }
})

As you can see, is a put function. Everything works as expected until .filter part (between Test2 and Test3 console logs). As I could see in the logs, filter is not filtering, is there anything I'm doing wrong? Thanks for the help

Edit 1 I am trying to check why filter is not workign with your proposals so I put this piece of code:

oldSection.learners.forEach(element => {
        console.log(`Test1: ${element._id}`)
        if (element._id === id) {
          console.log('true')
        } else if (element._id !== false) {
          console.log('false, id is: ' + id)
        }
      }

I am getting always false, the console output is:

ID to delete: 62d7cb8a7e0511313e442408
Test1: 62d7015e59f154f08cf5c13b
false, id is: 62d7cb8a7e0511313e442408
Test1: 62d7c9bea2d44917cdc01ad9
false, id is: 62d7cb8a7e0511313e442408
Test1: 62d7ca3d9a8b1507b235eb07
false, id is: 62d7cb8a7e0511313e442408
Test1: 62d7ca811e49d8aaba75d50a
false, id is: 62d7cb8a7e0511313e442408
Test1: 62d7cb0c06f6904ad0bd5dd9
false, id is: 62d7cb8a7e0511313e442408
Test1: 62d7cb8a7e0511313e442408
false, id is: 62d7cb8a7e0511313e442408
Test2: 62d7015e59f154f08cf5c13b
Test2: 62d7c9bea2d44917cdc01ad9
Test2: 62d7ca3d9a8b1507b235eb07
Test2: 62d7ca811e49d8aaba75d50a
Test2: 62d7cb0c06f6904ad0bd5dd9
Test2: 62d7cb8a7e0511313e442408

在您的示例数据中,您使用_id而不是id键:

oldSection.learners = oldSection.learners.filter(person => person._id !== id)

You can try this line of code to delete a learner from oldSection by _id :

const oldSection = {
    _id: '62d3f1d221aa21a03fe3bc21',
    name: 'Section',
    learners: [{
            _id: '62d6f9b64add603ff0d53257',
            name: 'Test 1'
        },
        {
            _id: '62d6fa5bfbdbbebc83a3923a',
            name: 'Test 2'
        }
    ]
};

const idToDelete = '62d6fa5bfbdbbebc83a3923a';

let updatedSection = {
    ...oldSection, 
    'learners': oldSection.learners.filter(learner => learner._id != idToDelete)
};

console.log(updatedSection);

// Output :

// {
//  "_id": "62d3f1d221aa21a03fe3bc21",
//  "name": "Section",
//  "learners": [
//      {
//          "_id": "62d6f9b64add603ff0d53257",
//          "name": "Test 1"
//      }
//  ]
// }

Finally solved with element._id.toString() === id as proposed in a comment in previous answer. Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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