nodejs multer用mongodb编辑上传的文件

lmyy7pcs  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(147)

我有一个网站,你可以上传文件。但我希望你也可以编辑它们。这意味着用户可以按编辑,然后把一个新的文件,它改变了数据库上的文件。与正常的文本,你可以做findByIdAndUpdate。但与异步函数,你可以。所以我的问题是我怎么能做到这一点。
这是我上传的代码

var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads");
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + "-" + Date.now() + ".png");
  },
});

var upload = multer({ storage: storage });

router.use(flash())

router.get("/create", (req, res) => {
  res.render("uploadPicture", {
    items: items,
    user: req.auth,
    title: "Upload",
  });
});

router.get("/", (req, res) => {
  image.find({}, (err, items) => {
    if (err) {
      console.log(err);
      res.status(500).send("An error occurred", err);
    } else {
      res.render("uploadPicture", {
        errMsg: req.flash('image'),
        items: items,
        user: req.auth,
        title: "pictures",
      });
    }
  });
});

router.post("/upload", upload.single("image"), async (req, res, next) => {
  //const userid = await user.findById({_id : userid});
  //console.log(userid);'
  const { folder } = sanitize(req.body);
  var obj = {
    name: req.body.name,
    userId: req.auth.userId,
    folder: folder,
    img: {
      data: fs.readFileSync(
        path.join(__dirname, "../uploads/" + req.file.filename )
      ),
      contentType: "image/png",
    },
  };
  image.create(obj, (err, items) => {
    if (err) {
      console.log("Test")
      console.log(err);
      req.flash('image', 'Image failed to upload!')
      res.redirect("/picture")
    } else {
      console.log(obj);
      items.save();
      req.flash('image', 'Image succesfully uploaded!')
      res.redirect("/picture")
    }
  });
});

module.exports = router;

下面是它自己尝试过但没有工作的方法,因为我得到了错误:TypeError:无法读取未定义的属性'findByIdAndUpdate'

router.post("/edit/:id", upload.single("image"), async(req, res ) =>{
  const id = req.params.id;
  console.log(req.params.id)
  const { folder } = sanitize(req.body);
  var obj = {
    name: req.body.name,
    userId: req.auth.userId,
    folder: folder,
  };
  if(req.body.image == ""){
    console.log("nothing here")
    image.findByIdAndUpdate(id, {name: req.body.name,folder: folder,}, function(err, docs){
      if (err) {
        console.log(err);
        req.flash('image', 'Image failed to upload!')
        res.redirect("/picture")
      } else {
        console.log(obj);
        req.flash('image', 'Image succesfully uploaded!')
        res.redirect("/picture")
      }
    })
  }else{
  var image = {
      img: {
        data: fs.readFileSync(
          path.join(__dirname, "../uploads/" + req.file.filename )
        ),
        contentType: "image/png",
      },
   }
   image.findByIdAndUpdate(id, {name: req.body.name,folder: folder,image: image}, function(err, docs){
    if (err) {
      console.log(err);
      req.flash('image', 'Image failed to upload!')
      res.redirect("/picture")
    } else {
      console.log(obj);
      req.flash('image', 'Image succesfully uploaded!')
      res.redirect("/picture")
    }
  })
  }

})

最后这部分有点乱,但我在尝试一些东西

t1qtbnec

t1qtbnec1#

我有一个解决方案如果有人要做这个以后

router.post("/edit/:id", upload.single("image"), async (req, res, next) => {
  const id = req.params.id;
  const { folder } = sanitize(req.body);
  if(req.file == null){
    console.log("text")
    try{
      const res = await image.findOneAndUpdate({_id:id}, {name: req.body.name,folder: folder})
      console.log(res.name + " " + res.folder + " " + res._id);
  }
  catch(err){
    console.log(err);
  }
  req.flash('imageView', 'ImageText succesfully to upload!');
  res.redirect("/view/" + req.params.id);
  }else{
    console.log("edit picture")
    try{
      const res = await image.findOneAndUpdate({_id:id}, {name: req.body.name,folder: folder, img: {data: fs.readFileSync(
      path.join(__dirname, "../uploads/" + req.file.filename )
    ),
      contentType: "image/png",
    }, })
      console.log(res.name + " " + res.folder + " " + res._id);
  }
  catch(err){
    req.flash('imageView', 'Image and text failed to upload!')
    res.redirect("/view/" + req.params.id)
    console.log(err);
  }
  req.flash('imageView', 'ImageText succesfully upload!');
  res.redirect("/view/" + req.params.id);
  }
})

我就是这么做的

相关问题