简体   繁体   English

使用Sequelize JS更新模型

[英]Updating model with Sequelize JS

I'm building a simple API with Express and Sequelize JS. 我正在使用Express和Sequelize JS构建一个简单的API。 I tried to update an record with req.School but nothing happend. 我试图用req.School更新记录,但是什么也没发生。 I shared the code below. 我分享了下面的代码。 Also I got no error for output. 我也没有输出错误。 Can you help me ? 你能帮助我吗 ?

Controller js 控制器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);
      });
    };

Route JS 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;

Since the params method, req.School is a sequelize object. 由于params方法,req.School是一个序列化对象。 Here is the params method. 这是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);
    });
};

As @Shivam said it' sa sequelize object, I could use provided methods. 正如@Shivam所说的,这是一个序列化对象,我可以使用提供的方法。 I want to soft delete my record, so here is my delete method with Sequelize JS. 我想软删除我的记录,所以这是我使用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 @PandhiBhaumik

Thank you for your help. 谢谢您的帮助。 I' ll try to use build method as a second option. 我将尝试使用build方法作为第二个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM