代码之家  ›  专栏  ›  技术社区  ›  Colin Ricardo

数组.拼接作品,Lodash.移除不

  •  3
  • Colin Ricardo  · 技术社区  · 8 年前

    我正在从具有 mongoose

    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);
      }
    };
    

    在上面的代码中,我使用 splice() ,工作正常。但是,洛达斯的 remove 不起作用。这个 documentation 对于 .remove() 说明它直接变异数组,所以为什么它在这里不起作用?

    2 回复  |  直到 8 年前
        1
  •  2
  •   Vlad274    7 年前

    简而言之,Mongoose和Lodash似乎不兼容(至少在这个用例中是这样)。


    猫鼬皮 Array.splice 用自己的方法。

    Mongoose source

    但是,Lodash显式调用默认值 数组.拼接 ,它绕过了包装版本。

    Lodash source

        2
  •  -3
  •   dmiranda2791    8 年前

    根据文件 remove “返回删除元素的新数组”。因此,为了实现您想要的,您需要将调用的返回值赋给用户.items.

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