【问题标题】:Unable to post data to MongoDB from an external API无法从外部 API 将数据发布到 MongoDB
【发布时间】:2022-04-08 04:01:25
【问题描述】:

我正在尝试从 外部 API 获取/获取数据并设置到我的 MongoDB 数据库中,但无法做到这一点,我的 MongoDB 对象在没有数据的情况下创建,尽管我使用 GET和 POST 带有 Hooks 的 API(UseState 和 UseEffect)。

我很困惑如何我能做到这一点,因为我想要获取的数据非常大,我不想一直请求获取数据,只有当我单击按钮数据获取并发送到我的 MongoDB 数据库,然后我从我的 MongoDB 中获取数据以供进一步使用。

MongoDB 数据库数据快照

你可以看到这里的对象中有一个空的数组而不是数据。

服务器代码

// import modules
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import path from "path";
import { createServer } from "http";
import { Server } from "socket.io";

import { stringToHash, varifyHash } from "bcrypt-inzi";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";
import postmark from "postmark";

const __dirname = path.resolve();

// Making some environment setting
const SECRET = process.env.SECRET || "12345";
const POSTMARK_KEY = process.env.POSTMARK_KEY;
const PORT = process.env.PORT || 5001;

const app = express();

let client = new postmark.ServerClient(POSTMARK_KEY);

// Connect MongoDB URL
mongoose.connect("mongodb://localhost:27017/myapp");

const rawData = mongoose.model("Raw Data", {
  created: { type: Date, default: Date.now },
  allData: [{}],
});

app.use(express.json());
app.use(cookieParser());

app.use(
  cors({
    origin: ["http://localhost:3000", "http://localhost:5001"],
    credentials: true,
  })
);

app.use("/", express.static(path.join(__dirname, "web/build")));
app.get("/", (req, res, next) => {
  res.sendFile(path.join(__dirname, "./web/build/index.html"));
});

// Row Data
app.get("/api/v1/rawData", (req, res) => {
  rawData
    .findOne({})
    .sort({ _id: "desc" })
    .exec(function (err, data) {
      res.send(data);
      // console.log(data);
    });
});

//path
app.use((req, res, next) => {
  jwt.verify(req.cookies.token, SECRET, function (err, decoded) {
    req.body._decoded = decoded;

    console.log("decoded: ", decoded); // bar

    if (!err) {
      next();
    } else {
      res.status(401).sendFile(path.join(__dirname, "./web/build/index.html"));
    }
  });
});

// Raw Data
app.post("/api/v1/rawData", (req, res) => {
  const newRawData = new rawData({
    allData: req.body.allData,
  });
  newRawData.save().then((data) => {
    console.log("Planning Data created");
    res.send("Planning Data created");
  });
});

app.get("/**", (req, res, next) => {
  res.sendFile(path.join(__dirname, "./web/build/index.html"));
});

const server = createServer(app);

const io = new Server(server, { cors: { origin: "*", methods: "" } });

io.on("connection", (socket) => {
  console.log("New client connected with id: ", socket.id);

  // To emit data to a certain client
  socket.emit("topic 1", "some data");

  // Collecting connected users in a array
  // connectedUsers.push(socket)

  socket.on("disconnect", (message) => {
    console.log("Client disconnected with id: ", message);
  });
});

server.listen(PORT, function () {
  console.log("server is running on", PORT);
});

反应用户界面

import * as React from "react";
import Button from "@mui/material/Button";
import axios from "axios";
import { myData } from "./myData";
import { useState, useEffect, useRef } from "react";

function PlanningData() {
  // usestate for raw data
  const [rawData, setRawData] = useState([]);

  // usestate for getting raw data from API
  const [arrayOfObject, setArrayOfObject] = useState({
    allData: [],
  });

  // API for setting raw data
  useEffect(() => {
    axios
      .get(`${baseUrl}/api/v1/rawData`, {
        withCredentials: true,
      })
      .then((res) => {
        console.log("getRawData:  ", res.data);
        setRawData(res.data);
      });
  }, []);

  // Refresh button to get the data
  const refresh = (e) => {
    axios
      .get(`https://script.google.com/macros/s/_____API-Key_____/exec`)
      .then((res) => {
        console.log(res.data.artical_Table);
        setArrayOfObject(res.data.artical_Table);
      })
      .catch((err) => {
        alert(`Something went wrong!\n${err}`);
      });
    e.preventDefault();
    setTimeout(() => {
      axios
        .post(
          `${baseUrl}/api/v1/rawData`,
          {
            allData: arrayOfObject.allData,
          },
          {
            withCredentials: true,
          }
        )
        .then((res) => {
          console.log("res: ", res.data);
        });
    }, 10000);
  };

  return (
    <div>
      {/* Button for Refresh */}

      <Button
        onClick={refresh}
        sx={{ m: 2.5 }}
        style={{
          display: "inline-block",
          padding: "8px",
        }}
        size="medium"
        variant="contained"
        color="primary"
      >
        Refresh
      </Button>
    </div>
  );
}

export default PlanningData;

获取表单API的数据类型

  artical_Table: [
    {
      style_no: "Sample",
      Item_description: "Sample",
      mon: "10000000-0",
      type: "Bags",
      oq: 1,
      force_update: 0,
      c_n: "Sample",
      pl_q: 0,
      os: "Open",
    },
    {
      style_no: "TNT-009738",
      Item_description:
        "Sack Bag 120x63cm Made From Cotton 100% cotton-black vat dyed 20x20/130x70 -250 GSM ? 60.5? FINISHED",
      mon: "21010186-15",
      type: "Bags",
      oq: 200,
      force_update: 2,
      c_n: "SEEGLER",
      pl_q: 200,
      os: "Open",
    },
    {
      style_no: "BAG-011662",
      Item_description: "Police Bag Black 56x60cm",
      mon: "22310008-1",
      type: "Bags",
      oq: 6500,
      force_update: 60,
      c_n: "Art Exhibition Textiles Ltd",
      pl_q: 6500,
      os: "Open",
    },
    {...},
    {...},
    {...},
    {...},
    {...},
    {...},
    .
    .
    .
    {...},
  ],
};

【问题讨论】:

  • 那究竟是什么不起作用?
  • 所有代码都在工作,但问题是我在 Snap 中提到的 MongoDB 数据中没有数据存储数组,allData 有一个空数组
  • 您可以考虑尽早将问题的信息发送至add,而不是在 cmets 中(without“编辑: "、"Update:" 或类似的 - 问题应该看起来好像是今天写的)。

标签: node.js reactjs mongodb express react-hooks


【解决方案1】:

你做错了。

当你更新 setArrayOfObject(res.data.artical_Table); 时,它会像 > arrayOfObject 等于 [{...},{...},...] .

您正在发送像arrayOfObject.allData 这样的数据,但是arrayOFObject 没有将allData 更新为对象数组。只需在您的帖子请求发送中执行此操作:

{allData:arrayOfObject}

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多