Remove ObjectId from objectId Array

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

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

What I'm trying to do is extend an array element equal to objectId, which I send from the user interface to the delete request.

The code I'm using is:

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

I am using the lodash library.

I am assuming there are ObjectId objects in the array, and I'm trying to compare with a string, which is request.params.itemId.

+5
source share
2 answers

I have a very similar setup with an "Event" object, which has an array of Assignment objects stored as an ObjectIds array. I could just use

 obj.arrayField.remove(idToRemove); 

Here is the relevant code inside 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); 
+2
source

You need to pass the string to mongoose.Types.ObjectId('') to get the actual object with which you can compare.

So _.remove(unit.items, mongoose.Types.ObjectId(req.params.itemId));

+1
source

Source: https://habr.com/ru/post/1238324/


All Articles