misterrodger
misterrodger

Reputation: 225

Send array from React to Express/Node to query Mongo

I am having difficulty sending an array of Id numbers from React state, through Node/Express, then eventually to MongoDB.

The main difficulty is how to send an array from React to the server. Once I have it there in a usable array form, I believe I know how to query MongoDB using an array.

I have been trying to do this mainly with a GET method and have been unsuccessful using req.params or req.query. I have tried this with several versions of string templates, and using what the Axios docs say as well as many other answers on stack overflow, none have been successful.

I have also tried a couple of versions of a PUT request and also with no success.

The array of Ids already exists in props.completedJobs:

In React:

  useEffect(() => {
    const fetchData = async () => {
      let completedJobsArray =  props.completedJobs;
      let json = JSON.stringify(data);
      let getData = {jsonData: json};
      const result = await axios('/api/brief/brief-array/' + getData);
      setData(result.data);
    };
    fetchData();

  }, []);

In Express app:


app.use("/brief", briefRouter);

then in the router:

router.get("/brief-array/:briefArray", briefController.brief_findArrayById);  

then the function:

exports.brief_findArrayById = async (req, res) => {
  try {
    // console.log("req.body: ", req.body);
    // console.log("req: ", req);
    // console.log("req.query: ", req.query);
    // console.log("req.params: ", JSON.stringify(req.params.briefArray));

    const briefs = await GWJob.find({"_id": {$in: ["5d1297512c68bc49060bce7b", "5d1297092c68bc49060bce7a"] } }); 
    res.json(briefs);
  } catch (err) {
    res.json({ message: err });
  }
}

The MongoDB query works with the hard-coded IDs, but cannot get any of the above versions of console.logs to display any value other than undefined or "object object".

I am also unable to query the database using an array through Postman.

I expect to send 1 or more id numbers in an array to MongoDB, and receive those documents back to React on the front end. Any help with sending an array from state in React through Node/Express is much appreciated! Thank you.

Upvotes: 0

Views: 2361

Answers (2)

misterrodger
misterrodger

Reputation: 225

Another attempt, still returning undefined. If anyone has links to a thorough resource on sending/receiving data I would much appreciate it. I always have spent days trying to get one of these to work, until I started using Axios, but if I need to go beyond what I can do with Axios I am back to square one. Many thanks.

useEffect(() => {
    const fetchData = async () => {    
    let completedJobsArray = props.completedJobs;
    let queryData = {completedJobsArray};

    const settings = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json; charset=utf-8'},
      body: JSON.stringify(queryData)
    };

    try {
      const fetchResponse = await fetch(`/api/brief/brief-array`, settings);
    const returnedData = await fetchResponse.json();
    setData(returnedData);
    } catch (error) {
      console.error("error: ", error);
    }
  }
  fetchData();
}, []);

Upvotes: 0

Eslam Abu Hugair
Eslam Abu Hugair

Reputation: 1208

You are sending Long string through the URL which is a limited length (~2047 char), the safe away to accomplish what you are trying to do to use a post or put method and send the list in the body.

Example:

useEffect(() => {
    const fetchData = async () => {
      let completedJobsArray =  props.completedJobs;
      const result = await axios({
                         method: 'post',
                         url: '/brief-array',
                         data: completedJobsArray
                        });
      setData(result.data);
    };
    fetchData();

  }, []);

Upvotes: 1

Related Questions