Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an ObjectId from an array of objectId

I have an objectId like this: ["56153e4c2040efa61b4e267f","56033932efefe0d8657bbd9e"] To save that information in my model I use:

items: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Items'
}]

What I'm trying to do is to pull an element of the array that is equal to objectId that I send from the front end in a delete request.

The code I'm using:

_.remove(unit.items, request.params.itemId);

I'm using lodash library.

The problem I suppose is that the array have ObjectId elements and I'm trying to compare with an string that is the request.params.itemId.

like image 522
Diego Avatar asked Sep 26 '22 22:09

Diego


1 Answers

I have a very similar setup with an "Event" object that has an array of "Assignment" objects saved as an array of ObjectIds. I was able to simply use

obj.arrayField.remove(idToRemove);

Here is the relevant code inside of my delete route handler:

var id = req.assignment._id;
req.event.assignments.remove(id);
req.event.save(function(err, event) {
    //etc 
}

Does this work for you?

unit.items.remove(request.params.itemId);
like image 100
Moshe Karmel Avatar answered Oct 11 '22 04:10

Moshe Karmel