Sequelize.js 返回关联表的旧值

我正在尝试更新产品的状态(产品表)。每个产品都有一个statusId,为“1”或“2”。


每个产品的 statusId 的默认值为“1”,如果访问一次路由,则应更改为“2”(反之亦然)。


“statusId”和“status”{“id”}应始终相同。


当我访问路由时,数据库中的“statusId”状态发生更改,但“status”的 HTTP 响应与数据库中的实际值不同。


响应示例:


{

    "id": 1,

    "name": "Drone",

    "barcode": "123456789",

    "description": "A drone that can fly",

    "image": "drone.jpg",

    "createdAt": "2020-12-22T17:30:15.000Z",

    "updatedAt": "2020-12-22T17:30:22.841Z",

    "statusId": 2,

    "status": {

        "id": 1,

        "name": "in",

        "createdAt": "2020-12-22T17:30:15.000Z",

        "updatedAt": "2020-12-22T17:30:15.000Z"

    }

}


协会:


db.status.hasMany(db.product, {

    foreignKey: {allowNull: false} ,


});

db.product.belongsTo(db.status, {

    foreignKey: {allowNull: false}

});


路线:


 app

        .route('/api/product/status/:id')

        .put([authJwt.verifyToken], controller.updateProductStatus);


控制器:


exports.updateProductStatus =  (req, res) => {

    // Get product with id and update status only

     Product.findOne({

        where: {

            id: req.params.id

        },

        include: [

            Status

        ]

    })

        .then(product => {

            let newStatus = product.statusId === 1 ? 2 : 1;

            product.update({

                statusId: newStatus

            })

                .then(

                    res.status(200).send(product)

                )

                .catch(err => {

                    console.log("Error (Update product): " + err);

                    res.status(404).send(err);

                })

        })

        .catch(err => {

            console.log("Error (find old product): " + err);

            res.status(404).send(err);

        });

};

如何更改代码以返回“status”的“id”的正确值?



大话西游666
浏览 50回答 1
1回答

慕尼黑8549860

您应该像这样重新加载模型实例:.then(  product.reload({ include: [Status]})    .then(res.status(200).send(product)) )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript