Click here to Skip to main content
15,885,182 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am getting this TypeError while posting data to mongodb using nodejs and express , I don't understand why I am geeting this error..! please help..!



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

https://i.stack.imgur.com/LZLwb.png[^]
Quote:
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..!


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;
E


What I have tried:

I don't understand what goes worng reactjs code or nodejs code..!
Posted
Updated 11-Feb-21 0:40am

1 solution

Found these.

Array.prototype.includes requires Node 6.
Node.js: "Array.includes is not a function" error : learnjavascript[^]

Below thread has solution for lower versions
javascript - Array.prototype.includes on Node js versions <= 4 - Stack Overflow[^]
 
Share this answer
 
Comments
Member 15069828 11-Feb-21 9:38am    
can You please show me in code..!
Member 15069828 11-Feb-21 12:09pm    
I don't get it please show me by code..! @thatraja
thatraja 11-Feb-21 13:00pm    
Did you check those links?
If your nodejs version is less than 6, your current code won't work.
2nd link says polyfill & indexOf is alternative for includes so try if (poll.options[option].indexOf(userId) !== -1)

Check the link for polyfill sample.

Frankly, you won't get instant code from Internet. You may need modify little bit most of time. So use search engines & programming forums to find more answers.
Member 15069828 12-Feb-21 6:27am    
my node version = v12.18.4, after using (poll.options[option].indexOf(userId) !== -1) still getting TypeError: poll.options[option].indexOf is not a function what to do ? @thatraja
thatraja 12-Feb-21 11:48am    
Those function(includes or indexof) are for array. Ensure your object is array. Also I guess this is nodejs code.

Don't work with too much code. Create a sample project & execute with minimum code(Like 10-15 lines code) which's better for you to avoid confusions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900