Search code examples
node.jsexpressmongoose

How to save user id value from database on server?


I have login/signup routes where I save a user to database. Every user has its own page where he can customize eveything. For example user changes his status. Status component makes ajax call to my server, and then my server tries to find a user from the curent session (I do not know how to do that) and then changes his status property in db.

I'm using React, Express, Mongoose.

I thought I coul'd save a user to my req object on /login or /signup route but this doesn't work.

api.get('/login', (req) => {
     ...getting data from req obj

     req.user = user

     ...doing other things
  });

Solution

  • The req object contains data coming in from the http call.

    For example if your react app made a GET request to this url

    http://localhost/user/123
    

    and you had defined a route in your express app like this

    router.get('user/:id', getUser());
    

    then you can access this request object to get the user id in the http url param.

    function getUser(req, res) {
    
         let user_id = req.params.id
    
    }
    

    with that user_id you can find a user in the mongodb using mongoose like this.

    function getUser(req, res) {
    
        let user_id = req.params.id;
    
        User.findOne({'_id': user_id}, (err, user) => {
    
            if(err) {
                return res.json(err);
            }
    
            return res.json(user);
    
        });
    
    }
    

    or you can update a user object

        function update(req, res) {
    
        let user_id = req.params.id;
        let avatar_url = req.body.avtar;
    
        User.findOne({ '_id': user_id }, (err, user) => {
    
            if (err) {
                return res.json(err);
            }
    
            user.avatar = avatar_url;
    
            user.save((err, user) => {
    
                if(err) {
                    return res.json(err);
                }
    
                return res.json(user);
    
            })
    
        });
    
    }
    

    Recommend you read this to learn the basics. http://mongoosejs.com/docs/guide.html https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4