1

I want to check if the id exists in the contacts array and pull the object that contains this id using mongoose. For instance, if i get the id - 5fe1c307330e711a6024697f, the first object should be deleted. i gave it a try but nothing happened. the data structure is looks like:

{
     _id: (id),
     contacts: [
         0: {
             _id: (id),
             id: '5fe1c307330e711a6024697f'
         }
         1: {
             _id: (id),
             id: '21412412412412412421421'
         }
}

And the code i've tried:

const { contactId, conversationId } = req.body;
const conversation = await Conversation.findById(conversationId);
const existingContacts = conversation.contacts;
existingContacts.map(existingContact => {
    if (existingContact.id === contactId) {
        let deletedContact = Conversation.findByIdAndUpdate(conversationId, {
            $pull: {
                  contacts: { id: contactId }
            }
        }
    }
})

1 Answer 1

1

It is just simple, don't need to map, it will delete/pull contactId,

const { contactId, conversationId } = req.body;
let deletedContact = Conversation.findByIdAndUpdate(
    conversationId,
    {
        $pull: {
            contacts: { _id: contactId }
        }    
    }
);
Sign up to request clarification or add additional context in comments.

Comments

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.