【问题标题】:How can I get the values inside the nested database?如何获取嵌套数据库中的值?
【发布时间】:2020-09-25 17:56:09
【问题描述】:

我想使用 req.body 从前端获取值到后端。但是它不适用于嵌套的实体,并且对于单个值它给我未定义。

这是我的猫鼬模式:

const mongoose = require('mongoose');


var DataSchema = new mongoose.Schema({

  chinese: {
    name: {
      type: String, 
      required: true
      },
    
    company: {
      type: String,
      required:  true,
    },  
    
  },
  other: {
    name: {
      type: String, 
      required: true
      },
    
    company: {
      type: String,
      required:  true,
    },
    madeIn:{
      type:String,
      required: true,
    },
    country:{
      type:String,
      required: false,
    },
    
  }
  ,
  productCategory: {
    mainCategory:{
      type: String,
      required: true,
    },
    subCategory:{
      type:String,
      required:false,
    }
  },
  date: {
    type: Date,
    default: Date.now
  },
  rating:{
    
  }
 

})


module.exports = mongoose.model('databaseEntries', DataSchema);

这就是我试图从中获取数据的方式:

router.post('/secretTop', (req, res) => {
  const data = new datab()

  //data.chinese.name=Req.body.chinese.name THIS GIVES ME "TypeError: Cannot read property 'name' of undefined"
  
  console.log(req.body.chinese)  // This gives me "undefiend"
  data.save()
    .then(() => { res.render('secretTop.pug', {msg: "Added Succesfully"}); 
    })
    .catch((err) => {
      console.log(err);
      res.render('secretTop.pug', {msg: "Something went wrong! Make sure no field is empty."})
}) 
})
当我像这样放置 req.body 时,我能够成功地运行它:
const data = new datab(req.body)

我想分别从前端获取所有值。

我已经在使用这样的 body-parser:

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

const bodyParser = require('body-parser');

//const router = express.Router();
//Body Parser

router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());

这是前端PUG文件:

extends layout

block style
    style
        include ../static/style1.css
    block title
        title Dev Page | altrNATIVE

block content
    .gradiantDiv
        -var message = msg || '';
        .messages
            .succMsg
                h2=message

        .formDiv
            form(action="/secretTop" method="POST" class="myEntries")

                .country
                    .chineseLabel
                        label(for="Chinese Name") Chinese Product Name:
                        input(type="text" id="productName" name="name" )
                        
                        label(for="Chinese Company" ) Product Company Name:
                        input(type="text" id="productCompany" name="chinese.company"  )

                    .otherLabel
                        label(for="Other Name") Alternative Product Name:
                        input(type="text" id="productName" name="other.name")
                        
                        label(for="Other Company" ) Company Name:
                        input(type="text" id="productCompany" name="other.company" )

                        label(for="Other Country" ) Company Country(Optional):
                        //select#country(name='other.country')

                        label(for="Other Made In") Made in:
                        textarea( name="other.madeIn" id="textInput")
                           
                    .commonProductType
                        label(for="Product Category") Product Category:
                        input(type="text" id="productCategory" name="productCategory.mainCategory")
                        label(for="Product Category") Sub Category (Optional):
                        input(type="text" id="subCategory" name="productCategory.subCategory" )
                        
                        
                       

                button.btn Submit
服务器:app.js

const express = require('express');

const path = require('path');

const routes = require('./routes/index');
const app = express();
app.use(express.json())
const bodyParser = require('body-parser');
//Body Parser

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/', routes)

//Static Directory
app.use(express.static(__dirname + '/static')); 
//Template Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');



module.exports = app;

用于初始化:start.js

const app = require('./app')
require('./models/database');

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/DataBaseMain', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(()=>{
    return console.log('MongoDB Connected...');
  })
  .catch(err=>console.log(err));



const server = app.listen(2000, () => {
    console.log(`Express is running on port ${server.address().port}`);
  });

【问题讨论】:

  • 你能不能也显示前端部分..
  • 已添加。请检查。
  • 在正文解析器 app.use(express.json()) 之前添加此内容并从快速路由器中删除注释
  • 不应该是router.use吗?
  • TypeError:无法读取未定义的属性“名称”。这就是我做 req.body.chinese.name 时得到的结果

标签: javascript html node.js express body-parser


【解决方案1】:

尝试摆脱所有这些:

app.use(express.json())
const bodyParser = require('body-parser');
//Body Parser

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

改为这样做:https://www.npmjs.com/package/body-parser#express-route-specific

const bodyParser = require("body-parser");

const app = express();

// Create `application/json` parser
const jsonParser = bodyParser.json();

app.post("/api/users", jsonParser, function(request, response) { /* ... */ });
//                     ~~~~~~~~~~

或者,如果您希望收到 JSON,请执行以下操作:

import { json } from "express";


app.post("/api/users", json(), function(request, response) { /* ... */ });
//                     ~~~~~~

我从未有过使用body-parser 作为顶级中间件的特别好的体验。

【讨论】:

  • 我试过了。它对我没有任何作用。我真的感到很有动力,因为我无法做到这一点。我不知道到底是什么问题。可能是架构吗?感谢您的回答。
  • 不,这与从前端发送的有效负载以及在后端接收该有效负载的路由有很大关系。您将要使用 Postman 和 Fiddler 进行调试,因为您可能是 a.) 省略 Content-Type,b.) 发送错误的 Content-Type,或 c.) body-parser 可能错误地检测到负载内容类型。现在你有太多的变量在起作用。
【解决方案2】:

我认为您在视图部分有误:

你刚刚写了name:

input(type="text" id="productName" name="name" )

应该是chinese.name:

input(type="text" id="productName" name="chinese.name" )

【讨论】:

  • 对不起,它只是 chinese.name 我忘了粘贴最近的更改。反正都是同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 2020-04-13
  • 2020-01-24
  • 2023-01-28
相关资源
最近更新 更多