使用schema.post的猫鼬递增或递减不递减

时间:2018-09-10 09:02:43

标签: node.js mongodb express mongoose

我正在尝试增加或减少用户广告的数量。我可以增加数字,但不能减少数字。

const updateUserAdsNumber = (saveOrDelete) => {
finalSchema.post(saveOrDelete, (ad, next) => {
    const increaseOrDecrease = saveOrDelete === 'save' ? 1 : -1;

    User.findOneAndUpdate(
        {_id: ad.adInfo.userId},
        {$inc: {adsPublished: increaseOrDecrease}},
        (err, user) => {
            if (err) return console.error('User ads could not increase or decrease', err.message);
        }
    );
    next();
 });
};

 updateUserAdsNumber('save');
 updateUserAdsNumber('deleteOne');

 finalSchema.plugin(mongooseUniqueValidator);

 const AdModel = mongoose.model('Ad', finalSchema);

以下是删除广告的路线:

router.delete('/:id', verifyTokenMiddleware, (req, res) => {
const id = req.params.id;
const {tokenDecoded} = req;
Ad.deleteOne({'adInfo.userId': tokenDecoded.userId, _id: mongoose.Types.ObjectId(id)}, (err) => {
    if(err){
        res.status(400).send({
            message: 'The ad could not be deleted. (Error_message = ' + err.message + ')'
        });
    } else {
        res.send({
            message: 'Ad deleted successfully!'
        })
    }
  })
});

我正在使用mongoose@5.2.13Mongo 3.6.5,可能出什么问题了?我可以将逻辑直接放入router.delete,但我更喜欢在模式导出之前将其挂接。

1 个答案:

答案 0 :(得分:0)

正如猫鼬的文档所述,我应该更新文档,而不是集合。因此,代替:

router.delete('/:id', verifyTokenMiddleware, (req, res) => {
const id = req.params.id;
const {tokenDecoded} = req;
Ad.deleteOne({'adInfo.userId': tokenDecoded.userId, _id: 
mongoose.Types.ObjectId(id)}, (err) => {
if(err){
    res.status(400).send({
        message: 'The ad could not be deleted. (Error_message = ' + err.message + ')'
    });
} else {
    res.send({
        message: 'Ad deleted successfully!'
    })
   }
 })
});

我用了这个:

router.delete('/:id', verifyTokenMiddleware, (req, res) => {
const id = req.params.id;
const {tokenDecoded} = req;
Ad.findById({'adInfo.userId': tokenDecoded.userId, _id: 
mongoose.Types.ObjectId(id)}, (err, ad) => {
    if (err) {
        res.status(500).send({
            message: 'The ad could not be deleted. (Error_message = ' + 
 err.message + ')'
        });
    } else {
        ad.remove(err => {    <---- here's the document remove
            if (err) {
                console.log(err);
            }
        });
        res.send({
            message: 'Ad deleted successfully!'
        });
    }
  });
});

,并在上面的第一个方法(在问题中)从updateUserAdsNumber('deleteOne')切换到updateUserAdsNumber('remove'),一切正常。