简体   繁体   English

模型未保存到MongoDB

[英]Model not saving to MongoDB

I'm working on a practice API to get used to creating models and routes, but can't seem to get my 1st route to save my data to my MongoDB. 我正在使用一种实践API来习惯于创建模型和路由,但是似乎无法获得将数据保存到MongoDB的第一条途径。

I get the following error from PostMan: 我从PostMan收到以下错误:

{
"message": {
    "errors": {
        "name": {
            "message": "Path `name` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `name` is required.",
                "type": "required",
                "path": "name"
            },
            "kind": "required",
            "path": "name"
        },
        "description": {
            "message": "Path `description` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `description` is required.",
                "type": "required",
                "path": "description"
            },
            "kind": "required",
            "path": "description"
        }
    },
    "_message": "Universes validation failed",
    "message": "Universes validation failed: name: Path `name` is required., description: Path `description` is required.",
    "name": "ValidationError"
}

} My model and route look like this: 我的模型和路线如下所示:

 const mongoose = require('mongoose'); const UniverseSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String, required: true }, date : { type: Date, default: Date.now } }); //export the route ---------------------Name in db , schema that it should use module.exports = mongoose.model('Universes', UniverseSchema); const express = require('express'); const router = express.Router(); const Universe = require('../models/Universe'); // Initial route that will render our universes page router.get('/', async (req , res) => { res.send('Universes Page'); try { const universes = await Universe.find(); res.json(universes); } catch (error) { res.json({ message: error }); } }); // Route use to create a universe // Create async our post router.post('/', async (req, res) => { // Create an instance of the Universe model const universe = new Universe({ name : req.body.name, description : req.body.description }); // Attempt to save our new universe with a try catch try { const savedUniverse = await universe.save() res.json(savedUniverse); console.log('saved'); } catch (error) { res.json({ message: error}); console.log('Not saved'); } }); module.exports = router; 

Whenever i pass my data through Postman I am sending a POST request with an object as such: { "name":"test1", "description":"test description 1" } This is my App.js file - including the body-parser 每当我通过邮递员传递数据时,我都会发送带有以下对象的POST请求:{“ name”:“ test1”,“ description”:“ test description 1”}这是我的App.js文件-包括主体-解析器

//Server setup
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv').config();

//Middleware
app.use(bodyParser.json());

//index Route
app.get('/' , ( req , res ) => {
    res.send('index');
});
// Import routes
const universeRoute = require('./routes/universes');
app.use('/universes', universeRoute );

//Connect to DB
mongoose.connect(process.env.DB_CONNECT,
     { useNewUrlParser: true } ,
     () => {
    console.log('Connected to DB');
});

app.listen(process.env.PORT || 5000);

Appreciate any and all help. 感谢所有帮助。

It's very likely the way you are sending the data to your API, and how it parses it. 很可能是您将数据发送到API的方式及其解析方式。

Try this: 尝试这个:

  1. Within Postman, use the most common used method format for sending data via POST requests. 在Postman中,使用最常用的方法格式通过POST请求发送数据。 This is: "raw" and send the data as application/json. 这是:“原始”并将数据作为application / json发送。 邮递员设置

  2. In the API side, make sure you are able to parse application/json requests. 在API方面,请确保您能够解析application / json请求。 The most used package for this withing Express is expressjs/body-parser Express中最常用的软件包是expressjs / body-parser

const mongoose= require('mongoose')
const express = require('express')
const bodyParser = require('body-parser')
const Universe = require('../models/Universe')

const app = express()

// Connect to MongoDB
mongoose.connect(/* MongoDB connection string */, /* Connection options */);
mongoose.connection.on('error', err => {
  console.error('MongoDB connection error: ' + err)
  process.exit(-1)
})

// parse JSON
app.use(bodyParser.json({ type: 'application/json' }))

// Initial route that will render our universes page
app.get('/', async (req , res) => {
  res.send('Universes Page')
  try {
      const universes = await Universe.find()
      res.json(universes)
  } catch (error) {
      res.json({ message: error })
  }
});

// Route use to create a universe
// Create async our post 
app.post('/', async (req, res) => {
  // Create an instance of the Universe model
  const universe = new Universe({
      name : req.body.name,
      description : req.body.description
  })
  //  Attempt to save our new universe with a try catch
  try {
      const savedUniverse  = await universe.save()
      res.json(savedUniverse)
      console.log('saved')
  } catch (error) {
      res.json({ message: error})
      console.log('Not saved')
  }
});

app.listen(3000)

And remember to validate bodies :) 并记得验证身体:)

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM