Asit singh
Asit singh

Reputation: 59

not getting data after posting data using POSTMAN

Here is my nodejs code where I comment out what I did with my code step by step and now I am going to post data using POSTMAN

   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.findByIdAndUpdate(pollId, {
  $set: { options: poll.options },
}, {new: true});
    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].indexOf(userId) !== -1) {
          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 posted data through POSTMAN getting nothing - Here you can see I posted data to my mongodb and getting just nothing here I posted data like { userId, answer } but getting blank array..! enter image description here

but when I check my ROBO-3T database - I am getting data -> enter image description here

My question is that why this is happing when getting data to my database but not on POSTMAN result ? please help

also I am getting this warning - (node:8776) DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify

Upvotes: 1

Views: 240

Answers (1)

eol
eol

Reputation: 24565

From the documentation:

By default, findByIdAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied.

So you can try setting the new option in the query options:

const update = await Poll.findByIdAndUpdate(pollId, {
              $set: { options: poll.options },
            }, {new: true});

Upvotes: 2

Related Questions