findOrCreate没有在我的数据库中查找数据

问题描述 投票:0回答:1

我创建了一个远程方法来对我的数据库进行多次查询,我想在那里找到最多可以同时创建12个用户模型。在loopback explorer中,我传递了这个数组,["player0", "player1", "player2"]到我的函数,我知道这些函数已经在我的数据库中了。但是,我遇到的问题是我返回状态200和一个空值数组。如果我传递不在DB中的名称,则返回每个名称的对象,其中包含所有默认值。所以我的问题是我的代码的查找部分出了什么问题?

我已经尝试将where子句添加到我的findOrCreate,它仍然返回一个null数组。

更新:这是整个方法


function getPlayerStats(names) {
  console.log('names: ', names);
  return new Promise((resolve, reject) => {
    const { Player } = app.models;
    const playerData = names.map(name => {
      console.log('single name: ', name);
      const defaultSkill = 1500;
      return Player.findOrCreate(
        { where: { name: name } },
        {
          name: name,
          careerSkill: defaultSkill,
          careerHighestSkill: defaultSkill,
          careerWins: 0,
          careerLosses: 0,
          careerPercent: 0,
          careerBestLeader: 'none',
          careerAllLeader: ['none'],
          highestCareerSkill: defaultSkill,
          careerSeasonWins: 0,
          careerSeasonLosses: 0,
          careerSeasonPercent: 0       
    }
      );
    });
    Promise.all(playerData)
      .then(results => resolve(results))
      .catch(err => reject(new Error('could not return results')));
  });
}

module.exports = { getPlayerStats };```
reactjs mongodb loopbackjs strongloop
1个回答
1
投票

我认为你应该在return Player.findOrCreate({name: name},正确版本的过滤器之前添加Player.findOrCreate({ where: { name: name } },...。此外,你可以省略回调(err) => {,因为你有catch

整个功能可能看起来像:player.js

   Player.getPlayerStats = function (names, cb) {

        const playerPromises = names.map(name => {
            const defaultSkill = 1500;
            return Player.findOrCreate({ where: { name: name } }, {
                "name": name,
                "careerSkill": defaultSkill,
                "careerHighestSkill": defaultSkill,
                "careerWins": 0,
                "careerLosses": 0,
                "careerPercent": 0,
                "careerBestLeader": "none",
                "careerAllLeader": ["none"],
                "highestCareerSkill": defaultSkill,
                "careerSeasonWins": 0,
                "careerSeasonLosses": 0,
                "careerSeasonPercent": 0
            })
        })


        Promise.all(playerPromises)
            .then(players => cb(null, players))
            .catch(err => cb(new Error('could not return results'), null))
    }
© www.soinside.com 2019 - 2024. All rights reserved.