【问题标题】:How can I parse an array value using node body-parser?如何使用节点正文解析器解析数组值?
【发布时间】:2018-06-25 20:57:03
【问题描述】:

我为表单上的字段创建了 mongoose 模式类型数组。我使用 like req.body.fieldName 将值作为属性访问,但是当我对数组执行此查询时,它返回 undefined 因为它不是键值对。如何在我的后路由处理程序中新创建的模型中解析它?

这是我的架构和我的后路由处理程序。

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

const StoreSchema = new Schema({
name : String,
  address: {
        street: String,
        crossStreet: String,
        city: String,
        state : String,
        zipcode : Number,
        country: String,
        formattedAddress: Array,
        location : {
            geoType : String,
            coordinates: Array
         }
     }

  })
module.exports = mongoose.model('Store', StoreSchema);

store.js 文件

const router = express.Router();
const Store = require('../models/store');

router.post('/api/store/register', (req, res, next) => {
      const store = new Store();
        store.address.street = req.body.street;
        store.address.crossStreet = req.body.crossStreet;
        store.address.city = req.body.city;
        store.address.state = req.body.state;
        store.address.zip = req.body.zip;
        store.address.country = req.body.country;
        store.address.formattedAddress = req.body.formattedAddress;
        store.location.geoType = req.body.geoType;
        store.location.coordinates = req.body.coordinates;
        store.save(() => {
            console.log('New store data is entered ' + store);
            res.redirect('/');
        });
})

【问题讨论】:

    标签: node.js express mongoose mongoose-schema body-parser


    【解决方案1】:

    第 1 步。npm install body-parser --save

    第 2 步。var bodyParser = require('body-parser')

    第 3 步。app.use(bodyParser.json());

    【讨论】:

    • app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended : true}));
    • 我的问题是如何从 formateAddress 和坐标中获取值?
    • <form action="/api/store/register" method="POST"> {this.renderFields()} <input type="file" name="store_logo"/> <div className="form-group"> <button type="submit" className="btn btn-login">Create Store</button> </div> </form>
    • 如果我注释掉坐标和格式化地址,代码可以工作
    • "address": { "street": "String", "crossStreet": "String", "city": "String", "state" : "String", "zipcode" : "Number", "country": "String", "formattedAddress": [], "location" : { "geoType" : "String", "coordinates": [] } }
    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多