我正在尝试删除数组中的每个项目(在本例中为产品记录)。但是,只删除一个项目。谁知道我做错了什么?提前谢谢!
app.post('/products/deletemulti', function (req, res, next) {
// Async function: Find all categories
var products = [1,2]; // Num products created
console.log(products);
// Update all products
async.eachSeries(products, function (product, next) {
console.log(product);
if (ObjectId.isValid(product)) {
Product.count({'_id': product}, function(error, count) {
if (count != 0) {
Product.remove({'_id': product}, function (error, product) {
if (error) return next(error);
else return next();
});
}
});
}
else return next();
});
res.send("Delete products.");
});
答案 0 :(得分:2)
async.eachSeries有三个参数。输入数组,迭代器函数和最终回调。你过早地调用res.send
,可能导致迭代器不能执行。
我已经清理了一下这段代码并添加了对响应的检查。
app.post("/products/deletemulti", function(req, res, next) {
// Async function: Find all categories
var products = [1, 2]; // Num products created
console.log(products);
// Update all products
async.eachSeries(
products.filter(ObjectId.isValid),
function(product, next) {
Product.count({ _id: product }, function(error, count) {
if (count != 0) {
Product.remove({ _id: product }, next);
}
});
},
function(err) {
if (err) {
res.status(400).send("Did not delete products");
} else {
res.send("Delete products.");
}
}
);
});