【问题标题】:Adding and deleting two collections with react functional components使用 react 功能组件添加和删除两个集合
【发布时间】:2020-03-23 14:35:06
【问题描述】:

我想通过一个操作添加两个集合。 第一个是使用 multer 和 gridfs-stream 的文件,第二个是基于文件的属性的文字。我所取得的成就: 1)literal based on file2)file uploaded。 在 1)(literal) 中,这个 fileID 属性与 2)(file) 的 _id 相同,并且 1) 中的 src 只是来自 2) 的文件名与一些路径连接。 在这里我必须解决问题。 首先是这个文字应该有更多的属性,但我在添加它们时遇到了问题。 这是模型(我认为没有任何问题,但它包含所需的所有道具):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const FileSchema = new Schema({
  fileID: {
    type: Schema.Types.ObjectId
  },
  src: {
    type: String,
  },
  altText: {
    type: String,
  },
  caption: {
    type: String,
  },
});

module.exports = File = mongoose.model('file', FileSchema);

最重要的 GET/POST 路由(以及第二个问题的 DELETE 路由):

router.get('/', (req, res) => {
  File.find()
    .sort({ date: -1 })
    .then(files => res.json(files))
});
// @route POST /upload
// @desc  Uploads file to DB
router.post('/', upload.single('file'), auth, (req, res) => {
  const newFile = new File({
    fileID: req.file.id,
    src: 'api/files/image/' + req.file.filename,
    altText: 'No image',
    caption: req.body.caption
  })
  newFile.save()

});

// @route GET /files
// @desc  Display all files in JSON
router.get('/', (req, res) => {
  File.find()
    .sort({ date: -1 })
    .then(files => res.json(files))
});

// @route GET /files/:filename
// @desc  Display single file object
router.get('/:filename', (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: 'No file exists'
      });
    }
    // File exists
    return res.json(file);
  });
});

// @route DELETE /files/:id
// @desc  Delete file
router.delete('/:id', auth, (req, res) => {
  gfs.remove({ _id: req.params.id, root: 'files' }, (err, gridStore) => {
    if (err) {
      return res.status(404).json({ err: err });
    }
  });
  File.findById(req.body.fileID)
    .then(file => file.remove().then(() => res.json({ success: true })))
    .catch(err => res.status(404).json({ success: false }));
});

和我的 React 组件最重要的片段:

const SliderModal = ({ isAuthenticated, addFile }) => {

  const [modal, setModal] = useState(false);
  const [file, setFile] = useState([]);
  const [slideData, setSlideData] = useState({
    fileID: '',
    src: '',
    altText: '',
    caption: '',
  })


  const toggle = () => {
    setModal(!modal);
  };

  const onChange = e => {
    setFile(e.target.files[0]);
    setSlideData({
      ...slideData,
      [e.target.name]: e.target.value
    });
  };

  const onSubmit = e => {
    e.preventDefault();

    const newFile = new FormData();
    newFile.append('file', file);
    // const { src, altText, caption, fileID } = slideData;

    // const newSlide = {
    //   fileID,
    //   src,
    //   altText,
    //   caption
    // }

    // Add file via addItem action
    addFile(newFile);
    // addFile(newSlide);

    // Close modal
    toggle();
  }

和下一部分(使用 reactstrap):

<Form onSubmit={onSubmit}>
            <FormGroup>
              {/* <Label for="caption">Caption</Label>
              <Input
                type="text"
                name="caption"
                id="caption"
                placeholder="Caption"
                className="mb-3"
                onChange={onChange}
              /> */}

              <Label for="file">File</Label>
              <Input
                type="file"
                name="name"
                id="file"
                placeholder="Add file"
                onChange={onChange}
              />
              <Button
                color="dark"
                style={{ marginTop: '2rem' }}
                block>
                Add File
                </Button>
            </FormGroup>
          </Form>

其中,当我取消注释时,我的模式中有文本输入,当我写任何东西时,我得到错误:Error while inputting text 第二个问题与删除文件有关。 此时我只能从数据库中删除一项(文字或文件)。 这是再次删除路线: // @route DELETE /files/:id // @desc 删除文件 router.delete('/:id', auth, (req, res) => { gfs.remove({ _id: req.params.id, root: 'files' }, (err, gridStore) => { 如果(错误){ 返回 res.status(404).json({ err: err }); } }); File.findById(req.body.fileID) .then(file => file.remove().then(() => res.json({ success: true }))) .catch(err => res.status(404).json({ 成功: false })); });

好的,我看到 File.findById 不是很好的功能,但问题是我想同时删除它们。这就是为什么在这个文字中我得出的结论是 fileID 属性,但我真的很困惑并且找不到解决方案。我的想法是通过这个 fileID 属性进行搜索,然后删除它们。 这是只删除文件的react函数(不要看是经过身份验证的,只是我只有在我的应用程序登录时才能删除文件):

{files.map(({ fileID}) => (
            < CSSTransition key={fileID} timeout={500} classNames="fade" >
              <ListGroupItem>
                {isAuthenticated ?
                  <Button
                    className="remove-btn"
                    color="danger"
                    size="sm"
                    onClick={onDeleteClick.bind(this, fileID)}
                  >&times;
                  </Button> : null}

              </ListGroupItem>
            </CSSTransition>
          ))}

【问题讨论】:

  • 简化你的问题并提出来,这样你就可以自己解决问题。您的问题太长了,而且涉及到任何有兴趣提供帮助的人。

标签: javascript reactjs multer gridfs gridfs-stream


【解决方案1】:

好吧,我只想一键删除两个对象。

router.delete('/:id', auth, (req, res) => {
  gfs.remove({ _id: req.params.id, root: 'files' }, (err, gridStore) => {
    if (err) {
      return res.status(404).json({ err: err });
    }
  })
  File.findOne(req.body.fileID)
    .then(file => file.remove().then(() => res.json({ success: true })))
    .catch(err => res.status(404).json({ success: false }));
});

不幸的是,这一次删除了两个对象,但不兼容。 此“文件”对象具有 fileID 属性,与 gfs 中的 id 相同。我的意愿是删除 id == fileID 的两个对象。

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2018-12-09
    • 1970-01-01
    • 2021-06-23
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多