我如何从这个尝试过的产品中删除说5bbee0b7e5fcb61df834f7d6的产品编号
router.post('/empty-cart', isLoggedIn, function(req, res, next) {
console.log("user" + req.body.user + ",product" + req.body.productId);
slug = req.body.productId;
user = req.body.user;
User.findOne({ _id: user }, {
$pull: { productId: slug }
}, function(err, model) {})
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
});
但是它似乎不适用于数组,因为它只考虑第一个元素来寻找建议
答案 0 :(得分:1)
您不能将$pull
与findOne
一起使用,而应该使用update
router.post('/empty-cart', isLoggedIn, function(req, res, next) {
console.log("user" + req.body.user + ",product" + req.body.productId);
slug = req.body.productId;
user = req.body.user;
User.update({ _id: user }, { $pull: { productId: slug } }, function(err, model) {
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
})
});
这是正确的方法。
答案 1 :(得分:0)
还有另一种方式。您应该先找到文档,然后再按ObjectId拉动。
router.post('/empty-cart', isLoggedIn, function (req, res, next) {
console.log('user' + req.body.user + ',product' + req.body.productId);
const slug = mongoose.Types.ObjectId(req.body.productId);
const user = req.body.user;
User.findOne({ _id: user }, function (err, model) {
if (err) return res.redirect('/error-page');
if (!model) return res.redirect('/notfound-page');
model.productId.pull(slug);
model.save(function (err) {
if (err) return res.redirect('/error-page');
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
});
});
});