Array.splice works, Lodash.remove doesn't

Viewed 411

I'm deleting an item from an array with mongoose. Some code:

const { find, remove } = require('lodash');

....

UserSchema.methods.deleteItem = async function (id) {
  const user = this;
  const item = find(user.items, i => i.id === id);
  const idx = user.items.indexOf(item);
  user.items.splice(idx, 1);

  // remove(user.items, i => i.id === id);

  try {
    await user.save();
    return item;
  } catch (err) {
    throw new Error(err);
  }
};

In the above code, I use splice(), which works correctly. However, lodash's remove doesn't work. The documentation for .remove() says that it mutates the array directly, so why does it not work here?

2 Answers

In short, Mongoose and Lodash do not appear to be compatible (at least for this use case).


Mongoose wraps Array.splice with its own method.

Please see line 568 of Mongoose source

However, Lodash explicitly calls the default Array.splice, which circumvents the wrapped version.

Please see (in order) lines 7847, 7864, 3857, 3866, 1484, 1435 of Lodash source

According to the docs remove "Returns the new array of removed elements". So in order to achieve what you want you need to assign the return value of the invokation to user.items.

https://lodash.com/docs/4.17.10#remove

Related