mongoose monggose的Model.save()在使用async/await时不更新MongoDB数据库中的documnet,然后阻止工作

1tu0hz3e  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(115)

我写的两个函数类似,但一个(其中有using then后保存())是不工作,另一个是工作,我使用异步/等待

这是工作

exports.update = async(req, res) => {
   const slug = req.params.slug.toLowerCase();
   try {
     let oldBlog=await  Blog.findOne({ slug }).exec();
     let form = new formidable.IncomingForm();
       form.keepExtensions = true;

       form.parse(req, async(err, fields, files) => {
           if (err) {
               return res.status(400).json({
                   error: 'Image could not upload'
               });
           }
           let { title, body, categories, tags } = fields;
           let { photo } = files;

           title = title && title[0];
           body = body && body[0];
           categories = categories && categories[0];
           tags = tags && tags[0];
           photo = photo && photo[0];

           let slugBeforeMerge = oldBlog.slug;
           oldBlog = _.merge(oldBlog, {title,body, categories, tags, photo});
           oldBlog.slug = slugBeforeMerge;

           

           if (body) {
               oldBlog.excerpt = smartTrim(body, 320, ' ', ' ...');
               oldBlog.desc = stripHtml(body.substring(0, 160));
           }

           if (categories) {
               oldBlog.categories = categories.split(',');
           }

           if (tags) {
               oldBlog.tags = tags.split(',');
           }

           if (photo) {
               if (files.photo.size > 10000000) {
                   return res.status(400).json({
                       error: 'Image should be less then 1mb in size'
                   });
               }
               oldBlog.photo.data = fs.readFileSync(photo.filepath);
               oldBlog.photo.contentType = photo.mimetype;
           }

          const result=await oldBlog.save();
          res.json(result);
       });

   } catch (err) {
      return res.status(400).json({
               error: errorHandler(err)
           }); 
   }
   
};

字符串

这个不行

exports.update = (req, res) => {
  const slug = req.params.slug.toLowerCase();
  
  Blog.findOne({ slug })
    .exec()
    .then((oldBlog) => {
      let form = new formidable.IncomingForm();
      form.keepExtensions = true;

      form.parse(req, (err, fields, files) => {
        if (err) {
          return res.status(400).json({
            error: 'Image could not upload',
          });
        }

        let { body, title, categories, tags } = fields;
        let { photo } = files;

        title = title && title[0];
        body = body && body[0];
        categories = categories && categories[0];
        tags = tags && tags[0];
        photo = photo && photo[0];

        let slugBeforeMerge = oldBlog.slug;
        oldBlog=_.merge(oldBlog, {title,body,categories, tags, photo});
        oldBlog.slug = slugBeforeMerge;

        if (title) {
          oldBlog.title = title;
        }
        if (body) {
          oldBlog.excerpt = smartTrim(body, 320, ' ', ' ...');
          oldBlog.desc = stripHtml(body.substring(0, 160));
        }

        if (categories) {
          oldBlog.categories = categories.split(',');
        }

        if (tags) {
          oldBlog.tags = tags.split(',');
        }

        if (photo) {
          if (photo.size > 10000000) {
            return res.status(400).json({
              error: 'Image should be less then 1mb in size',
            });
          }
          oldBlog.photo.data = fs.readFileSync(photo.filepath);
          oldBlog.photo.contentType = photo.mimetype;
        }
      });
      return oldBlog.save();
    })
    .then((result) => res.json(result))
    .catch((err) =>
      res.status(400).json({
        error: errorHandler(err),
      })
    );
};


请有人告诉我,我在下面的代码块错误,所以不工作
我想知道为什么then/catch代码不工作,而async/await工作,并且两个代码非常相似

a1o7rhls

a1o7rhls1#

我正在缩短你的代码,排除不相关的部分:

exports.update = (req, res) => {
  const slug = req.params.slug.toLowerCase();
  
  Blog.findOne({ slug })
    .exec()
    .then((oldBlog) => {
      // do something with your document
      oldBlog
        .save()
        .then((result) => res.json(result));
      });
    })
    .catch((err) =>
      res.status(400).json({
        error: err.message
      })
    );
};

字符串

相关问题