【问题标题】:(node: 5088) UnhandledPromiseRejectionWarning: ValidationError: Dev validation failed: name: Path `name` is required(节点:5088)UnhandledPromiseRejectionWarning:ValidationError:开发验证失败:名称:需要路径“名称”
【发布时间】:2019-12-18 10:39:03
【问题描述】:

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

【问题讨论】:

  • response 的值是多少?我猜当您将值传递给猫鼬时,它会导致猫鼬验证错误。

标签: node.js mongodb express mongoose schema


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 2020-10-03
      • 1970-01-01
      相关资源
      最近更新 更多