【问题标题】:Working with nested javascript objects returns empty object使用嵌套的 javascript 对象返回空对象
【发布时间】:2019-04-23 12:49:10
【问题描述】:

我有一个正在尝试注册用户的应用程序。在我的中间件实现中,我有一个代码,当他们输入他们的名字和姓氏、电子邮件和密码时,它会创建一个用户对象。但是,当我控制台记录新用户对象时,这些属性不会更新。只需控制台记录它返回未定义的名字。在我的架构中,名字、姓氏和电子邮件是嵌套的。

我已经尝试使用点符号来访问架构中的特定属性。

用户架构

const userSchema = mongoose.Schema({ 
    empID: {
        type: String,
        trim: true
    },
    password: {
        type: String,
        required: true
    },
    userInfo: {
        lastName: {
            type: String,
            trim: true 
        },
        firstName: {
            type: String, 
            trim: true
        }
    },
    contactInfo: {
        email: {
            type: String,
            required: true
            unique: true,
        },
        phone: [{
            home: {
                type: String,
                trim: true
            },
            mobile: {
                type: String,
                trim: true
            }
        }]
    } 

用户路线

router.post('/register', UserController.createUser);

用户控制器

exports.createUser = (req, res, next) => {

console.log("Before creating user");

//Creates new user
let newUser = new User({
   firstName: req.body.firstName,
   lastName: req.body.lastName,
   email: req.body.email,
   password: req.body.password
});

console.log(req.body.firstName);
console.log(newUser.toJSON());

【问题讨论】:

  • console.log(req.body.firstName); 返回undefined ?
  • 是的。并且整个对象只显示哪些内部对象中有一个数组
  • 你能登录 req.body 吗?在用户构造函数中,您应该将相应地嵌套到您的架构中。如userInfo.firstName: req.body.firstName
  • console.log(req.body); 返回一个{ }。我试过了,它说应该是“,”
  • 您是如何拨打请求电话的?

标签: javascript node.js mongoose


【解决方案1】:

由于没有您的 app.js 文件的示例,所以我在这里在黑暗中拍摄... 尝试使用:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

https://www.npmjs.com/package/body-parser

【讨论】:

  • 抱歉,我确实使用了 body-parser。我刚刚注释掉 app.use(bodyParser.json()); 现在当我 console.log(req.body) 它显示我在表单字段中输入的所有内容
猜你喜欢
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多