简体   繁体   中英

(node: 5088) UnhandledPromiseRejectionWarning: ValidationError: Dev validation failed: name: Path `name` is required

Server.js

const express = require('express'); const mongoose =
require('mongoose');

const routes = require('./routes');

const server = express();

mongoose.connect("mongodb+srv://izaac:izaac@cluster0-hzrrk.mongodb.net/omnistack8?retryWrites=true&w=majority",
{   useNewUrlParser: true });

server.use(express.json()); server.use(routes);

server.listen(3333);

routes.js

const express = require('express'); const DevController =
require('./controllers/DevController');

const routes = express.Router();

routes.post('/devs', DevController.store);

module.exports = routes;

Dev.js

const { Schema, model } = require('mongoose');

const DevSchema = new Schema({  name: {         type: String,       required:
true,   },      user: {         type: String,       required: true,         },  bio:
String,     avatar: {       type: String,       required: true,     }, }, {
timestamps: true, });

module.exports = model('Dev', DevSchema);

DevController.js

const axios = require('axios'); 
const Dev = require('../models/Dev');

module.exports = {  
  async store(req, res) {       
    const { username } = req.body;
        const userExists = await Dev.findOne({ user: username });

        if (userExists) {           
      return res.json(userExists);      
    }

        const response = await axios.get(`https://api.github.com/users/${username}`);
        const { name, bio, avatar_url: avatar } = response.data;
        const dev = await Dev.create({          
       name,            
       user: username,          
       bio,
       avatar       
    });

     return res.json(dev);  
  } 
};

enter image description here

“名称”字段是必需的,但对您的请求的响应没有“名称”。

在您的架构设计中,键name是必需的,因此您需要记录将在Dev.create()传递的数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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