简体   繁体   English

如何使用 REACTJS、NODEJS、EXPRESSJS 和 MONGODB 中的 API 进行 POST 数据?

[英]How can do POST data using API from REACTJS ,NODEJS,EXPRESSJS AND MONGODB?

I am getting this TypeError: poll.options[option].includes is not a function while posting data to mongodb using nodejs and express, I don't understand why I am geeting this error... please help..!我得到这个 TypeError: poll.options[option].includes is not a function 同时使用 nodejs 和 express 将数据发布到 mongodb,我不明白为什么我会收到这个错误......请帮助..!

 exports.votes = async (req, res, next) => {
  try {
    /**
     * 1. get the poll from db
     * 2. check if the user already exists in any option
     * 3. if user has already selected any option do nothing
     * 4. if user has selected any other option remove from that option
     * 5. if user does not exist in any option, insert his user id to selected option
     */
    const { pollId } = req.params;
    console.log(pollId);
    let { userId, answer } = req.body;
    console.log(userId);
    console.log(answer);
    // get selected poll from db
    const poll = await Poll.findById(pollId);
    if (answer && poll) {
      answer = answer.toLowerCase();
      ///Finf the Poll

      let existingVote = null;
      Object.keys(poll.options).forEach((option) => {
        // loop on all options, check if the user already exists in any option
        if (poll.options[option].includes(userId)) {
          existingVote = option;
        }
      });
      if (existingVote == null) {
        // if there is no existing vote save it to db
        try {
          const push = {};
          push[`options.${answer}`] = userId;
          const update = await Poll.findByIdAndUpdate(
            pollId,
            { $push: push },
            { upsert: true }
          );
          res.status(201).json(update);
        } catch (err) {
          error.status = 400;
          next(error);
        }
      } else if (existingVote && existingVote.length > 0) {
        // check if answer is same as previous, if yes send not modified
        if (existingVote.toLowerCase() === answer.toLowerCase()) {
          res.status(304).send("Response already saved");
        } else {
          // delete the previous response and save it in new
          if (
            Array.isArray(poll.options[existingVote]) &&
            poll.options[existingVote].length > 0
          ) {
            // TODO: filtering this is not returning array but 1
            poll.options[existingVote] = poll.options[existingVote].filter(
              (vote) => vote != userId
            );
            poll.options[answer] = poll.options[answer].push(userId);
            const update = await Poll.findByIdAndUpdate(pollId, {
              $set: { options: poll.options },
            });
            res.status(201).json(update);
          }
        }
      } else {
        error = {
          status: 500,
          message: "Something went wrong",
        };
        next(error);
      }
    } else {
      error = {
        status: 404,
        message: "Poll not found",
      };
      next(error);
    }
  } catch (error) {
    error.status = 400;
    next(error);
  }
}

but whenever I posting data to POSTMAN got no error so why is that... enter image description here here is my React code --> please chack- here whenever handalchange work I am getting all the console.log but nodemon crash and get { TypeError: poll.options[option].includes is not a function } so please help..!但是每当我将数据发布到 POSTMAN 时都没有错误,所以为什么...在此处输入图像描述是我的 React 代码->请在此处查看-每当handalchange工作时,我都会得到所有的 console.log,但 nodemon 崩溃并得到 { TypeError: poll.options[option].includes is not a function } 所以请帮忙..!

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.css";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import axios from "axios";
import { API } from "../../backend";

const MainPoll = () => {
  const userId = isAutheticated() && isAutheticated().user._id;
  const [polls, setPoll] = useState([]);
  const [error, seterror] = useState(false);

  useEffect(() => {
    loadPoll();
  }, []);

  const loadPoll = () => {
    getPolls().then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setPoll(data);
        console.log(data);
      }
    });
  };

  // Handling user vote
  // Increments the votes count of answer when the user votes
  const handalchange = async (pollId, userId, answer) => {
    console.log(pollId);
    console.log(userId); // getting
    console.log(answer); // getting
    await axios.post(`${API}/vote/${pollId}`, { userId, answer });
    // postPoll(pollId, { userId, vote }).then(() => {
    //   loadPoll();
    // });
  };

  return (
    <div className="">
      <div className="container my-5">
        <h1 className="blog_heading my-3">Poll's of the Day</h1>
        <div className="row">
          {polls.reverse().map((poll, index) => (
            <div className="col-lg-4 col-12 poll_border" key={index}>
              <Poll
                noStorage
                question={poll.question}
                answers={Object.keys(poll.options).map((key) => {
                  return {
                    option: key,
                    votes: poll.options[key].length,
                  };
                })}
                onVote={
                  (answer) =>
                    handalchange(poll._id, userId, answer, console.log(answer)) // getting vote
                }
                className="mb-2"
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MainPoll;

I don't understand what goes worng reactjs code or nodejs code..!我不明白 reactjs 代码或 nodejs 代码是怎么回事……! please help请帮忙

Your poll options are not initialized with an Array , so it generates this error.您的投票选项未使用Array初始化,因此会生成此错误。 Try using default: [] in the mongoose schema for options or otherwise use this wherever you are adding/pushing options.尝试在 mongoose 架构中使用default: []作为选项,或者在添加/推送选项的任何地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM