Updating the user in the req.user

22 views
Skip to first unread message

shyam...@gmail.com

unread,
Jan 22, 2018, 5:09:39 AM1/22/18
to nodejs

Hi All ,

I am taking a full stack react course from an online learning platform, in which I am using node and express as the server, passport for authentication and MongoDB as the backend database. So I have a flow where when the user logs in a cookie is attached to the user, so on subsequent request from the user, the cookie is deserialized and the user record from the DB is stored in the req.user.

So I have a billing system which uses the stripe, where when the amount is charged he can create surveys (say $1 for 1 credit). Now I have the user model in the mongo db as

user: 
{ _id: abc,
googleId: xyz,
__v: 0,
credits: 0 },
Once when the user pays the amount the credits has to be updated and it has to be reflected in the front end in the header.

const keys = require('../config/keys')
const stripe=require('stripe')(keys.stripeSecretKey);

app.post('/api/stripe',async (req,res) => {
const charge = await stripe.charges.create({
amount: 500,
currency: "usd",
source: req.body.id, // obtained with Stripe.js
description: "$5 for 5 credits"
})

req.user.credits +=5;
const user = req.user.save(); 
});
};

My question is: How come changing the req.user and saving it updates the user model in the DB. As in the above code, I could not see any import for the mongoose user model?

I was expecting something like import the user model -> get the user id from req.user -> then use findById() -> to identify the user in MongoDB and then make the change in the credits.

Reply all
Reply to author
Forward
0 new messages