猿问

Axios 发布错误 TypeError: Cannot read property

我正在使用 MERN Stack 构建一个模拟 facebook 应用程序。当我尝试将帖子保存到我的数据库时,它不断抛出两个错误。一个在后端说TypeError: Cannot read property 'create' of undefined,另一个在前端说Unhandled Rejection (Error): Request failed with status code 500


这是我的前端 API.js 页面


import axios from "axios";


export default {

  // Gets all posts

  getPosts: function() {

    return axios.get("/api/users/posts");

  },

  // Gets the post with the given id

  getPost: function(id) {

    return axios.get("/api/users/posts/" + id);

  },

  // Deletes the post with the given id

  deletePost: function(id) {

    return axios.delete("/api/users/posts/" + id);

  },

  // Saves a post to the database

  savePost: function(postData) {

    return axios.post("/api/users/posts", postData);

  }

};

这是我的 handleSubmit 函数


handleFormSubmit = (event) => {

        // Preventing the default behavior of the form submit (which is to refresh the page)

        event.preventDefault();

        

        // Saving post to database

        API.savePost(this.state)

        .then(data => {

          console.log("data: ", data);

          this.setState({

            title: data.data.title,

            body: data.data.body,

            

          });


        });

      };

这是我的后端 postController.js,TypeError: Cannot read property 'create' of undefined被抛出的地方。


const db = require("../models");

console.log("--------------------------------------");

console.log("Controller Reached");

console.log("--------------------------------------");

// Defining methods for the postController

module.exports = {

  findAll: function(req, res) {

    console.log("----------------------findAll------------------------  ");

    console.log("req.query: ", req.query);

    db.User.posts

      .find(req.query)

      .sort({ date: -1 })

      .then(dbModel => res.json(dbModel))

      .catch(err => res.status(422).json(err));

  },

  findById: function(req, res) {

    db.User.posts

      .findById(req.params.id)

      .then(dbModel => res.json(dbModel))

      .catch(err => res.status(422).json(err));

  },

慕桂英4014372
浏览 230回答 1
1回答

忽然笑

User.posts是undefined因为.posts是 的实例的属性User。因此,您需要先实例化用户。在这种情况下,通过从 User 集合中查找现有对象。由于您定义User.posts为原始数组,而不是引用另一个集合,因此代码将如下所示。create: function (req, res) {  // 1. find the existing user (I guess passport does the job)  db.User.findById(req.body.userid).then((user) => {    // 2. add an post    user.posts.push({      title: req.body.title,      body: req.body.body,      postedBy: req.body.userid,      dateCreated: Date.now(),      comments: [],    });    // 3. persist the changes    user.save();  });}如果你想分离集合,我认为这更好,你需要在分离的集合上创建一个新对象,并引用发布的用户。// Post schemavar postSchema = new Schema({  title: String,  body: String,  postedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },  dateCreated: Date,  comments: [{ body: "string", by: mongoose.Schema.Types.ObjectId }],});// The controllercreate: function(req, res) {  // 1. find the existing user (or you get id from Passport session)  db.User.findById(req.body.userid).then((user) => {    // 2. add an post set "postedBy" as the user    return Post.create({      postedBy: user._id,      title: req.body.title,      body: req.body.body,      dateCreated: Date.now(),    });  });}以下是有关引用的官方文档:https ://mongoosejs.com/docs/populate.html希望这可以帮助。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答