(节点:5088)UnhandledPromiseRejectionWarning:ValidationError:开发人员验证失败:name:路径`name`是必需的

时间:2019-08-11 15:17:47

标签: node.js mongodb express mongoose schema

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

2 个答案:

答案 0 :(得分:1)

“姓名”字段为必填项,但对您的请求的响应中没有“姓名”。

答案 1 :(得分:0)

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