Jakob
Jakob

Reputation: 139

How to add to User Object Node.JS

I'm new to node so bear with me!

I am working on my auth system. I have login, register and logout done so far. Now I want to update my user in the settings page. How would I go about updating the already added User items such as username, password and email? And most importantly adding new ones such as API Key, and API Secret.

Here is my code:

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

My user schema, the api key info is not added on registration. Should it be in the schema or will it be added automatically later?

    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');
                });

How I create the new user after verification.

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

Where I get the API keys from a form and then want to insert them into the User that is currently logged in. This is where my problem is.

Thank you in advance for any help!

Upvotes: 2

Views: 1148

Answers (1)

Talha Awan
Talha Awan

Reputation: 4619

Assuming you've access to the logged in user in req like 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
          }
      });

});

And yes you should keep all the fields you want to insert even in future in the schema. Else they won't insert into database.

Upvotes: 3

Related Questions