sequelizejs更新数据问题,求解 - CNode技术社区

sequelizejs更新数据问题,求解
发布于 10 年前 作者 tomoya92 6071 次浏览 最后一次编辑是 9 年前 来自 问答

场景是博客 常见一个博客,会选择一个类别,当编辑保存的时候会判断类别是否变了,如果变了,就将以前的类别-1,新选择的类别+1,然后我就碰到问题了。。

更新博客源码:

exports.update = function(req, res) {
 var id = req.body.id;
 var title = req.body.title;
 var content = req.body.content;
 var oldCategoryId = req.body.oldCategoryId;
 var categoryId = req.body.categoryId;
 var isYuanChuang = req.body.isYuanChuang;
 var img = req.body.img;
 async.series({
 upload: function(next) {
 if (req.file) {
 var key = req.file.filename;
 var localFile = req.file.path;
 qiniuupload.uploadFile(key, localFile, function(err, ret) {
 if (err) {
 console.log(err);
 } else {
 img = CONFIG.qn_access.origin + "/" + ret.key;
 //删除本地文件
 fs.unlinkSync(localFile);
 next();
 }
 })
 } else {
 next();
 }
 },
 save: function(next) {
 Blog.update({
 title: title,
 content: content,
 updateAt: Date.now(),
 categoryId: categoryId,
 isYuanChuang: isYuanChuang,
 img: img
 }, {
 where: {
 id: id
 }
 }).then(function(result) {
 next();
 });
 }
 }, function(err, result) {
 if (oldCategoryId != categoryId) {
 //修改前的类别-1
 Common.updateBlogCount(oldCategoryId, false);
 //修改后的类别+1
 Common.updateBlogCount(categoryId, true);
 }
 res.redirect("/admin/blog/list");
 });
};

common.js里的updateBlogCount()方法

//修改类别里博客数量
//action == true ++ false --
exports.updateBlogCount = function(categoryId, action) {
 Category.findOne({
 id: categoryId
 }).then(function(result) {
 console.log(result.id, result.name, result.blogCount, categoryId);
 var count = 0;
 if (action == true) {
 count = result.blogCount + 1;
 } else {
 count = result.blogCount - 1;
 }
 Category.update({
 blogCount: count
 }, {
 where: {
 id: categoryId
 }
 }).then(function() {});
 });
};

updateBlogCount()方法里的console.log(result.id, result.name, result.blogCount, categoryId);打印出来的数据分别是:

6 'java' 1 '6'
6 'java' 1 '7'

categoryId分别是6,7,可查询出来的类别对象确实id为6的数据,求解这是为啥?

3 回复

我觉得的是:这两个函数的顺序问题: 让Common.updateBlogCount返回promise:

 Common.updateBlogCount(oldCategoryId, false).then(function(){
	 Common.updateBlogCount(categoryId, true);
	 });

试试看!

@htoooth 我逗比了,findOne()方法用错了,正确写法是这样的

//修改类别里博客数量
//action == true ++ false --
exports.updateBlogCount = function(categoryId, action) {
 Category.findOne({
 where: {
 id: categoryId
 }
 }).then(function(result) {
 console.log(result.id, result.name, result.blogCount, categoryId);
 var count = 0;
 if (action == true) {
 count = result.blogCount + 1;
 } else {
 count = result.blogCount - 1;
 }
 Category.update({
 blogCount: count
 }, {
 where: {
 id: categoryId
 }
 }).then(function() {});
 });
};

好吧,我错了

回到顶部

AltStyle によって変換されたページ (->オリジナル) /