0

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

2
  • 1
    Shouldn't that be .filter(person => person._id !== id) with an underscore before the id? Commented Jul 20, 2022 at 9:04
  • Thanks but I also tried that and got the same result Commented Jul 20, 2022 at 9:11

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

In your example data, you use _id not id keys:

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

5 Comments

Thanks for the answer. That was example data but in real app it comes from the database. I tried with .id and ._id and got the same result
If it comes from the database, then _id is probably an object whereas id is a string, so they will always be unequal when compared with !==.
Thanks, I updated the question with more info, seems very strange
Test1: 62d7cb8a7e0511313e442408, false, id is: 62d7cb8a7e0511313e442408 demonstrates that element._id === id is false even if element._id.toString() === id might be true.
Wow, it worked with toString method!! You saved me a lot of headaches. Thanks a lot @HeikoTheißen
0

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"
//      }
//  ]
// }

5 Comments

Thanks but same result :(
what result do you get ?
I get the same array learners, with no change
This doesn't modify oldSection, it create an updated version named updatedSection which for me contains only one learner
I edited with the full code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.