【问题标题】:How to add to User Object Node.JS如何添加到用户对象 Node.JS
【发布时间】:2017-08-05 20:50:41
【问题描述】:

我是 node 新手,请耐心等待!

我正在开发我的身份验证系统。到目前为止,我已经完成了登录、注册和注销。现在我想在设置页面中更新我的用户。我将如何更新已添加的用户项目,例如用户名、密码和电子邮件?最重要的是添加新的 API Key 和 API Secret。

这是我的代码:

var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index:true
    },
    email: {
        type: String
    },
    password: {
        type: String
    },
    apiKey: {
        type: String
    },
    apiSecret: {
        type: String
    }
});

我的用户架构,注册时未添加 api 密钥信息。它应该在架构中还是稍后会自动添加?

    var newUser = new User({
                username: username,
                email:email,
                password: password
            });
User.createUser(newUser, function(err, user){
                    if(err) throw err;
                    console.log(user);
                    req.flash('success_msg', 'You are registered and can now login');

                    res.redirect('/users/login');
                });

验证后如何创建新用户。

router.post('/settings', function(req, res){
    var apiKey = req.body.apiKey;
    var apiSecret = req.body.apiSecret;
    //INSERT api info into DB here
});

我从表单中获取 API 密钥,然后想将它们插入到当前登录的用户中。这就是我的问题所在。

提前感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb express mongoose database


    【解决方案1】:

    假设您可以访问 req 中的已登录用户,例如 req.user

    router.post('/settings', function(req, res) {
        var updateFields = {
            apiKey: req.body.apiKey,
            apiSecret: req.body.apiSecret
        }
    
        User.findOneAndUpdate({"_id": req.user._id}, {"$set": updateFields}, {"new": true}})
          .exec(function(err, user) {
              if (err) {
               //handle err
              } else {
               //user contains updated user document
              }
          });
    
    });
    

    是的,即使将来您也应该将所有要插入的字段保留在架构中。否则他们不会插入到数据库中。

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2019-01-30
      • 2014-06-28
      • 1970-01-01
      • 2016-10-24
      • 2014-06-25
      • 2014-09-14
      • 2023-01-19
      • 1970-01-01
      相关资源
      最近更新 更多