ReferenceError: _id is not defined

Viewed 1328

Trying to pass in an _id to allow my comments to post to my front end React app. When I test express route in postman I don't get the comment . See screen shot below. When I try to post the comment I get the reference error _id id not defined.

Update: The _id is fixed with id: data._id but I am not able to see my comments when I test in browser: enter image description here

Here is backend express/node GalleryController.js

const mongoose = require('mongoose');
const Posts = mongoose.model('posts');

exports.PostGalleryInput = async (req, res) => {
  console.log(req.body);
  await new Posts({
    body: req.body,
    _id: req.params.id
  }).save(async (err, data) => {
    if (err) {
      console.log('err:', err);
      res.status(500).json({
        message: 'Something went wrong, please try again later.'
      });
    } else {
      res.status(200).json({
        message: 'Post Created',
        data,
        id: _id
      });
    }
  });
};

Here is Data Schema:

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema(
  {
    id: String,
    title: String,
    body: String,
    name: String,
    url: String,
    comment: String
  },
  {
    collection: 'posts'
  }
);

module.exports = mongoose.model('posts', PostSchema);

Here is front end React component

import React, { useState, useEffect } from 'react';
import Container from 'react-bootstrap/Container';
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';
import axios from 'axios';
import './css/sharewall.css';

const Cards = () => {
  const [posts, setPosts] = useState([]);
  const [comment, setComment] = useState('');

  const loadPosts = async () => {
    try {
      let res = await axios.get(`http://localhost:5000/getall`);
      setPosts(res.data.reverse());
    } catch (error) {
      console.log(error);
    }
  };

  function saveComment(e, _id) {
    e.preventDefault();
    axios({
      method: 'POST',
      url: 'http://localhost:5000/postinput',
      data: {
        _id: _id,
        comment: comment
      }
    })
      .then((res) => {
        loadPosts();
      })
      .catch((err) => {
        console.log(err);
      });
  }

  const loadComment = async () => {
    try {
      let res = await axios.post('http://localhost:5000/postinput');
      setComment(res.data.comment._id);
      console.log(res.data.comment._id);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    loadPosts();
    loadComment();
  }, []);

  return (
    <div className="compoentclass">
      <Container className="mt-5 ml-auto mr-auto">
        <div className="text-center">
          {posts.map(
            (post) =>
              post.url && (
                <div key={post._id}>
                  <Card className="">
                    <Card.Img alt="" src={post.url} />
                    <Card.ImgOverlay className="overlay">
                      <Card.Title className="d-flex justify-content-center align-items-center">
                        <Card.Text className="cardStyle text-light">{post.body}</Card.Text>
                      </Card.Title>
                    </Card.ImgOverlay>
                  </Card>

                  <div>
                    <Card.Text>{post.comment}</Card.Text>
                  </div>

                  <textarea
                    className="comment text-center mt-3 mb-3"
                    onChange={(e) => setComment(e.target.value)}
                    name="comment"
                    type="text"
                  />

                  <div className="d-flex justify-content-start mt-n3 mb-4">
                    <Button
                      className="shareButton"
                      variant="secondary"
                      onClick={(e) => saveComment(e, post._id)}
                    >
                      Comment
                    </Button>
                  </div>
                </div>
              )
          )}
        </div>
      </Container>
    </div>
  );
};

export default Cards;

enter image description here

0 Answers
Related