【问题标题】:Trying to post data to MongoDB, get status code 200 but fail to post data尝试向 MongoDB 发布数据,获取状态码 200 但无法发布数据
【发布时间】:2020-12-09 00:38:04
【问题描述】:

我是编程新手。

现在,我正在做一个 MERN 堆栈项目,试图将数据发布到我的 mongoDB 数据库,但经过多次尝试都失败了。

数据库:

在同一个数据库中有 2 个集合,“items”和“users”。架构如下:

项目架构:

const mongoose  = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ItemSchema = new Schema(
  {
  entryDate: {
    type: Date,
    required: true
  },
  leaveDate: {
    type: Date,
    required: true
  }
  },
  {
    collection: 'items'
  }
);

module.exports = Item = mongoose.model('Item', ItemSchema);

用户架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  userName: {
    type: String,
    required: true
  },
  Password: {
    type: String,
    required: true
  }
});

module.exports = User = mongoose.model('users', UserSchema);

前端:

handleClick = (e) => {
    const API_URL = 'http://localhost:5000/api/users/';

    this.setState({
      startDate: this.handleStartDate(e.target.value),
      endDate: this.handleEndDate(e.target.value)
    });

    const newDate = {
      startDate: this.state.startDate,
      endDate: this.state.endDate
    }

    const data = JSON.stringify(newDate);

    axios({
      method: 'post',
      url: API_URL + 'addnew',
      data: data,
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
        "Accept": "application/json"
      }
    })
      .then(response => {
        if (response.status === 200) {
          console.log('The status code is : ' + response.status);
        }
      })
      .catch(err => {
        console.log('-------Failed to add new data. Error occurred.-------');
      });
  };

后端:

// @route  POST api/items
// @desc   Create An Item
// @access Public 
router.post('/addnew', function(req, res) {
  const newItem = new Item({
    entryDate: req.body.entryDate,
    leaveDate: req.body.leaveDate
  });

  console.log(newItem);
  // save model to database
  newItem.save(function(err) {
    if (err) {
      res.json({
        success: false,
        message: 'failed to post data'
      })
    } else {
      res.json({
        success: true,
        message: 'success to post data'
      })
    }
  })
});

我用Postman测试过后端API,状态码是200,但是返回错误信息,如下截图所示:

Screenshot of Postman

我不确定我哪里出错了,我的猜测是架构“项目”的数据无法保存到集合“项目”中,但我不知道该怎么办。

对于每一个小小的帮助,我将不胜感激。提前致谢!

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    试着像这样改变

    const Item = require('path/to/ItemSchemas');
    
    // @route  POST api/items
    // @desc   Create An Item
    // @access Public 
    router.post('/addnew', function(req, res) {
      const newItem = new Item({
        entryDate: req.body.entryDate,
        leaveDate: req.body.leaveDate
      });
    
      console.log(newItem);
      // save model to database. Since newItem hasn't been added to the db, we used Item.save instead
      Item.save(newItem, function(err) {
        if (err) {
          // save to db failed!
          res.status(500).json({
            success: false,
            message: err
          })
        } else {
          res.json({
            success: true,
            message: 'success to post data'
          })
        }
      })
    });
    

    【讨论】:

    • 感谢您的帮助!我尝试了此代码,但在使用 Postman 进行测试时出现“500 - 内部服务器错误”。由于我分别为这两个模式创建了两个集合“项目”和“用户”,这会自动将数据保存到集合“项目”还是我需要在代码中指定?
    • 啊,我没有意识到这一点,对不起,我快速阅读了您的帖子。由于您使用项目constructir const newItem = new Item.... 实例化您的实例,因此您不应使用User.save,而是使用Item.save。此外,您应该在连接上添加一些日志,以确保您连接到您的 mongo 实例而没有任何错误
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多