簡體   English   中英

使用Sequelize JS更新模型

[英]Updating model with Sequelize JS

我正在使用Express和Sequelize JS構建一個簡單的API。 我試圖用req.School更新記錄,但是什么也沒發生。 我分享了下面的代碼。 我也沒有輸出錯誤。 你能幫助我嗎 ?

控制器js

module.exports.params = function(req, res, next, id) {
School.find({
          where: {
            id: id
          }
        })
        .then(function(school) {
          if (!school) {
            next(new Error("School not found by given ID"));
          }else {
            req.School = school;
            next();
          }
        }, function(err) {
          next(err);
        });
    };
module.exports.delete = function (req,res,next) {
    req.School.Status = SysEnums.Deleted;
      School.update(req.School,{
        where:{
          id:req.School.id
        }
      }).then(function (deleted) {
        res.json(deleted);
      });
    };

JS線

var router = require("express").Router();
var controller = require("../Controllers/SchoolController");

router.param("id",controller.params);

router.route("/").get(controller.get);

router.route("/:id").get(controller.getOne).delete(controller.delete);

module.exports = router;

由於params方法,req.School是一個序列化對象。 這是params方法。

module.exports.params = function(req, res, next, id) {

  School.find({
      where: {
        id: id
      }
    })
    .then(function(school) {
      if (!school) {
        next(new Error("School not found by given ID"));
      }else {
        req.School = school;
        next();
      }
    }, function(err) {
      next(err);
    });
};

正如@Shivam所說的,這是一個序列化對象,我可以使用提供的方法。 我想軟刪除我的記錄,所以這是我使用Sequelize JS的刪除方法。

module.exports.delete = function(req, res, next) {

  try {
    req.School.Status = SysEnums.Deleted;
    req.School.save().then(function(entity) {
      res.json(entity);
    });
  } catch (e) {
    console.log(e);
  }
};

@PandhiBhaumik

謝謝您的幫助。 我將嘗試使用build方法作為第二個選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM