簡體   English   中英

使用 React 功能組件添加和刪除兩個集合

[英]Adding and deleting two collections with react functional components

我想通過一個操作添加兩個集合。 第一個是使用 multer 和 gridfs-stream 的文件,第二個是基於文件的具有屬性的文字。 那是我取得的成就: 1)基於文件的文字2)上傳的文件 在 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>

其中,當我取消注釋時,我在模態中輸入了文本,其中,當我寫任何東西時,我收到錯誤:輸入文本時出錯第二個問題與刪除文件有關。 此時我只能從數據庫中刪除一個項目(文字或文件)。 這是 DELETE 路由: // @route DELETE /files/:id // @desc 刪除文件 router.delete('/:id', auth, (req, res) => { gfs.remove({ _id: req. params.id, root: '文件' }, (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( { 成功:假 })); });

好吧,我看到 File.findById 不是很好的函數,但問題是我想同時刪除它們。 這就是為什么在這個文字中我得出了 fileID 屬性的結論,但我真的很困惑並且找不到解決方案。 我的想法是同時按此 fileID 屬性進行搜索,然后將其刪除。 這是僅刪除文件的反應函數(不要看它已通過身份驗證,那只是我只能在登錄我的應用程序時刪除文件):

{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>
          ))}

好吧,我只想一鍵刪除兩個對象。

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 }));
});

不幸的是,這一個刪除了兩個對象,但不兼容。 這個 'File' 對象有 fileID 屬性,與 gfs 中的 id 相同。 我的意願是刪除兩個 id == fileID 的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM