Ad

Remove An ObjectId From An Array Of ObjectId

- 1 answer

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.

Ad

Answer

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);
Ad
source: stackoverflow.com
Ad