【问题标题】:API patch and put doesn't update version fieldAPI 补丁和 put 不更新版本字段
【发布时间】:2021-10-27 23:11:45
【问题描述】:

我目前正在尝试构建一个以 Node.js 作为后端的应用程序。

在询问了使用什么 API 方法进行更新后,因为我最初使用 post for all,我开始使用 put 和 patch 问题已解决,补丁没有更新我的数据库中的版本字段。

我调用 put 和 patch 的方式有问题还是它们就是这样

router.patch('/update/:id', async (req, res) => {
    // get category id
    const id = req.params.id;
    // check if category is found
    try {
        const category = await Category.findByIdAndUpdate(id, req.body);
        // check if no category is found
        if (!category) {
            return res.status(400).send('Category not found');
        }
        // return category
        return res.status(200).send(category);
    }
    catch (err) {
        return res.status(400).send(err);
    }
});

before update

after update

【问题讨论】:

    标签: javascript node.js mongodb mongoose ecmascript-6


    【解决方案1】:

    尝试将此添加到您的类别架构中:

    schema.pre('update', function( next ) {
      this.update({}, { $inc: { __v: 1 } }, next );
    });
    

    【讨论】:

    • 我发现 .save() 可以解决这个问题,但这也很好用,抱歉延迟重播
    【解决方案2】:

    __v 会在必要时由 Mongoose 自动增加。是猫鼬内部使用的,所以更新文档时不用增加。只要对数组的修改可能会更改任何数组的元素位置,该值就会自动递增。它将应用于整个数组的操作:$pull$pullAll$pop$set

    【讨论】:

    • 我发现了问题,我需要在更新后保存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    相关资源
    最近更新 更多