Reputation: 49
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 }
}
}
}
})
Upvotes: 1
Views: 31
Reputation: 36144
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 }
}
}
);
Upvotes: 1