首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Node.js express中根据此模型和控制器更新用户详细信息

如何在Node.js express中根据此模型和控制器更新用户详细信息
EN

Stack Overflow用户
提问于 2018-12-18 17:38:46
回答 1查看 699关注 0票数 0

我正在尝试更新设置页面中的用户数据。他/她可以更改所有详细信息,如姓名、姓氏、生日等。下面是auth控制器:

代码语言:javascript
复制
module.exports = {
      async CreateUser(req, res) {
        const schema = Joi.object().keys({
          username: Joi.string()
            .min(4)
            .max(10)
            .required(),
          email: Joi.string()
            .email()
            .required(),
         firstName: Joi.string()
            .required(),
          lastName: Joi.string()
            .required(),
           position: Joi.string()
            .required(),
          password: Joi.string()
            .min(5)
            .required(),
        });

        const { error, value } = Joi.validate(req.body, schema);
        if (error && error.details) {
          return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
        }

        const userEmail = await User.findOne({
          email: Helpers.lowerCase(req.body.email)
        });
        if (userEmail) {
          return res
            .status(HttpStatus.CONFLICT)
            .json({ message: 'Email already exist' });
        }

        const userName = await User.findOne({
          username: Helpers.firstUpper(req.body.username)
        });
        if (userName) {
          return res
            .status(HttpStatus.CONFLICT)
            .json({ message: 'Username already exist' });
        }

        return bcrypt.hash(value.password, 10, (err, hash) => {
          if (err) {
            return res
              .status(HttpStatus.BAD_REQUEST)
              .json({ message: 'Error hashing password' });
          }

          const age = moment().diff(moment([value.byear, value.bmonth - 1, value.bday]), 'years');
          const body = {
            username: Helpers.firstUpper(value.username),
            email: Helpers.lowerCase(value.email),
            firstName: value.firstName,
            lastName: value.lastName,
            position: value.position,
            password: hash,
          };
          User.create(body)
            .then(user => {
              const token = jwt.sign({ data: user }, dbConfig.secret, {
                expiresIn: '5h'
              });
              res.cookie('auth', token);
              res
                .status(HttpStatus.CREATED)
                .json({ message: 'User created successfully', user, token });
            })
            .catch(err => {
                res
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .json({ message: 'Error occured' });
            });
          });
        },

用户模型

代码语言:javascript
复制
const userSchema = mongoose.Schema({
  username: { type: String },
  email: { type: String },
  isVerified: { type: Boolean, default: false },
  firstName: { type: String },
  lastName: { type: String },
  position: { type: String },
  password: { type: String },

我想我应该有一条这样的路线:

代码语言:javascript
复制
router.post('/user/settings', AuthHelper.VerifyToken, user.editUser);

根据上面的CreateUser功能,它应该是什么样子的editUser控制器?我在前端使用了Angular。但我觉得这无关紧要。我假设90%应该与CreateUser相同,但是到底应该更改什么,以便用户可以在设置表单中更新他/她的详细信息并更改模型中的数据?

EN

回答 1

Stack Overflow用户

发布于 2018-12-19 06:24:57

因此,您希望更新用户的一些字段(如firstName、lastName等),而不是替换整个信息。然后,您可能希望首先获取当前用户的数据,然后只更新那些允许的字段。

请找到下面的示例代码。

代码语言:javascript
复制
/**
 * User router
 */
router.put('/user/:userId', AuthHelper.VerifyToken, user.editUser);

// This function will be triggered when Express finds matching route parameter
router.param('userId', function (req, res, next, id) {
    User.findOne(id, function (err, user) {
        if (err) {
            next(err);
        } else if (user) {
            // When it finds user information, bind that to request object, which will be used in the other middlewares.
            req.user = user;
            next();
        } else {
            next(new Error('failed to load user'));
        }
    });
});

/**
 * User controller
 */
exports.editUser = (req, res, next) => {
    let { user } = req;

    // You pick only allowed fields from submitted body
    const allowedFields = { firstName: req.body.firstName, lastName: req.body.lastName, birthday: req.body.birthday };

    // Override the current user data with new one
    user = Object.assign(user, allowedFields);

    user.save((err, savedUser) => {
        if (err) {
            return next(err);
        }
        res.json(savedUser.toJSON());
    });
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53830114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档