我为表单上的字段创建了mongoose模式类型数组。我使用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('/');
});
})
答案 0 :(得分:0)
第1步。npm install body-parser --save
第2步。var bodyParser = require('body-parser')
第3步。app.use(bodyParser.json());