【发布时间】:2018-09-10 19:54:57
【问题描述】:
我正在使用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(),它可以正常工作。但是,lodash 的remove 不起作用。 .remove() 的 documentation 表示它直接对数组进行变异,那为什么在这里不起作用?
【问题讨论】:
-
您将其显示为
remove()而不是_.remove()。这是一个错字……还是答案? -
@charlietfl 我也看到了
find,所以我猜OP可能使用了const {find, remove} = _;。 -
@zero298 啊……可能是对的。不过问也无妨
-
@zero298 是的,没错,很好。现在添加到问题中! :)
-
我以前没有使用过 mongoose,但是没有理由让 lodash 的 remove 表现得像你描述的那样。所以,我有问题:1)你为什么不认为它有效? IE 您在哪里以及如何检查值而没有看到“预期”状态? 2)什么是user.items?它是一个普通的旧javascript数组还是猫鼬做了一些特殊的包装?
标签: javascript mongoose lodash