node.js - 更新数据库中现有的用户数据

标签 node.js mongodb express passport.js

目前,我已成功将用户信息保存在我的数据库中。但是,如果 Steam 数据库中的信息发生更改,我想在用户登录时更新数据库中的用户信息。所以我的数据库里面也是一样的。

以下是我的用户架构中的信息示例

const UserSchema = mongoose.Schema({
  username:{
    type: String,
  },
  profileURL:{
    type: String,
  },
  profileImageURL:{
    type: String,
  },
  steamId:{
    type: String,
  }
});

下面是我的 app.js 的示例。当用户登录时,我检查用户 steamId 是否存在于我的数据库中,我想更新用户信息,例如用户名、profileURL、profileImageURL 及其 steamID(如果存在),否则我在数据库中创建一个新用户。我怎样才能实现这个目标?目前,我只是返回done(null, user)。

passport.use(new SteamStrategy({
    returnURL: 'http://localhost:3000/auth/steam/return',
    realm: 'http://localhost:3000/',
    apiKey: ''
    }, 
    function (identifier, done){
        var steamId = identifier.match(/\d+$/)[0];
        var profileURL = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + 'api_Key' + '&steamids=' + steamId;

        User.findOne({ steamId: steamId}, function(err, user){
            if(user){
                return done(null, user); 
            }
            else{
                request(profileURL, function (error, response, body){
                    if (!error && response.statusCode === 200) 
                    {
                        var data = JSON.parse(body);
                        var profile = data.response.players[0];
                        var user = new User();
                        user.username = profile.personaname;
                        user.profileURL = profile.profileurl;
                        user.profileImageURL = profile.avatarfull;
                        user.steamId = steamId;
                        user.save(function(err){
                            done(err, user);
                        });
                    }
                    else
                    {
                        done(err, null);
                    }
                });
            }
        });
}));

最佳答案

您可以通过启用 upsert 的更新调用来完成此操作。尝试这样的事情:

        request(profileURL, function(err, response, body){
          var data = JSON.parse(body);
          var user = {
          //... construct user object
          }
          
          User.findOneAndUpdate({ steamId: steamId }, user, {upsert: true, new: true, setDefaultsOnInsert: true}, function(err, newUser){
            if (err) return handleError(err);
            done(null, newUser);
          });
        });

关于node.js - 更新数据库中现有的用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440150/

相关文章:

javascript - node.js 表单处理更新和删除

node.js - ElasticSearch 多字段搜索查询

javascript - 如何在 Node.js 中使用 Promise 对 API 进行递归请求?

javascript - express |异步发出多个http请求

node.js - 将环境变量从 grunt 传递到文件

node.js - 我可以使用 Firebase Cloud Functions 隐藏 JavaScript 代码吗?

java - 如何使用自定义注释存储和加载加密值

node.js - 如何访问 express 的 uploadDir 属性?

node.js - 使用 REST 进行环回电子邮件验证(其中配置了所需的 verifyOptions)

MongoDB Sum-Query 不求和