Is there a way to update user info with mongoose?

I’m working on a personal project and stumbled upon this problem. I’ve managed to make my (steam)users save to mongodb through mongoose. Right now I’ve made it .save() a new user only when it’s not already found in the DB. But what if someone changes their steam nickname or picture and log-in again, they will have the ones I initially saved. Any way to only update changes to a user in the database?
thanks.

app.get('/auth/steam/return',
  passport.authenticate('steam', { failureRedirect: '/' }),
  function(req, res) {
    const user = new User({ //create user object on schema
      name: req.user.displayName,
      steam64: req.user.id
    });
    User.findOne({steam64: req.user.id}, function(err, user1){ //try to find user by id in DB
      if(err){ // catch error
        console.log(err);
      }
      if(user1){console.log('user found, proceeding...')} // user was found in DB
      if(!user1){ //user not found, writing to DB
        console.log('no user found with that id, writing.')
          user.save()
          .then((result) => {
            console.log('user saved successfully !')
          })
          .catch((err) => { // catch & print error
            console.log(err);
          });
      }   
    });
    res.redirect('/');
  });

42 thoughts on “Is there a way to update user info with mongoose?”

  1. you can use findOneAndUpdate() with option {upsert:true} and also new : true to return the document after update was applied.

    User.findOneAndUpdate({steam64: req.user.id},{
         name: req.user.displayName,
         steam64: req.user.id
    },{new : true, upsert: true}) 
    
    Reply

Leave a Comment