如果节点 js

问题描述

我有一个控制器和一个这样的模型。

const update = async (req,res,next) => {
  try {
    const payload = req.body;

    if (req.file) {
      const tmp_path = req.file.path;
      const originalExt = req.file.originalname.split(".")[
        req.file.originalname.split(".").length - 1
      ];
      const filename = req.file.filename + "." + originalExt;
      const target_path = path.resolve(rootPath,`public/upload/${filename}`);

      const src = fs.createReadStream(tmp_path);
      const dest = fs.createWriteStream(target_path);
      src.pipe(dest);

      src.on("end",async () => {
        try {
          const product = await Product.findOne({ _id: req.params.id });
          const currentimage = `${rootPath}/public/upload/${product.image_url}`;

          if (fs.existsSync(currentimage)) {
            fs.unlinkSync(currentimage);
          } else {
            return res.json("File does not exist");
          }

          const newProduct = await Product.findOneAndUpdate(
            { _id: req.params.id },{ ...payload,image_url: filename },{ new: true,runValidators: true }
          );

          return res.json(newProduct);
        } catch (err) {
          if (err && err.name === "ValidationError") {
            return res.json({
              error: 1,message: err.message,fields: err.errors,});
          }
          next(err);
        }
      });

      src.on("error",async () => {
        next(err);
      });
    } else {
      const product = await Product.findOneAndUpdate(
        { _id: req.params.id },payload,runValidators: true }
      );
      await product.save();

      return res.json(product);
    }
  } catch (err) {
    if (err && err.name === "ValidationError") {
      return res.json({
        error: 1,});
    }
    next(err);
  }
};
const { Schema,model } = require("mongoose");

const productSchema = Schema(
  {
    name: {
      type: String,minlength: [3,"Please enter at least 3 characters"],required: [true,"The name field is required"],},description: {
      type: String,maxlength: [1000,"Please enter less than 1000 characters"],price: {
      type: Number,default: 0,image_url: String,{ timestamps: true }
);

module.exports = model("products",productSchema);

代码运行良好。但是当我的姓名字段为空并将数据发送给邮递员时,会出现验证错误“需要姓名”,但图像数据已替换为新的。

我希望验证失败时,代码不执行任何操作,以下代码不运行

if (fs.existsSync (currentimage)) {
     fs.unlinkSync (currentimage);
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...