即使有现有记录,环回findOrCreate也会创建新记录

时间:2018-08-01 09:52:57

标签: javascript node.js loopbackjs

据我对回送文档的理解,Persistedmodel.findOrCreate应该根据查询找到一个模型并返回它,或者如果该模型不存在,则在数据库中创建一个新条目。

在我的案例中,我注意到无论它是否存在,它都会创建一个新条目。

不确定我缺少什么。这是我的代码:

teams-joined.json

{
  "name": "teamsJoined",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "teamID": {
      "type": "string",
      "required": true
    },
    "playerID":{
      "type":"string",
      "required":true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

teams-joined.js

let queryThatWorks = {where:{
              and: [
                  {teamID: teamID}
              ]
            }
         };

let query = {where:{
              and: [
                  {teamID: teamID},
                  {playerID: req.currentUser.id},
              ],
            }
         };
let joinTeamsData = {
              teamID: teamID,
              playerID: req.currentUser.id,
            };
console.log(query.where,'query');
teamsJoined.findOrCreate(query, joinTeamsData,
     function(err, data, created) {
                console.log(data,created);
              });

当我多次校准API时,这就是我得到的

{ and:
   [ { teamID: 'bf36e0-93a5-11e8-a8f4-9d86f4dd79ee' },
     { playerID: '5b20887bb6563419505c4590' } ] } 'query'
{ teamID: 'bf36e0-93a5-11e8-a8f4-9d86f4dd79ee',
  playerID: '5b20887bb6563419505c4590',
  id: 5b61798534fa410d2b1d900a } 'data'
true 'created'
{ and:
   [ { teamID: 'bf36e0-93a5-11e8-a8f4-9d86f4dd79ee' },
     { playerID: '5b20887bb6563419505c4590' } ] } 'query'
{ teamID: 'bf36e0-93a5-11e8-a8f4-9d86f4dd79ee',
  playerID: '5b20887bb6563419505c4590',
  id: 5b61798634fa410d2b1d900b } 'data'
true 'created'

我希望它在创建时返回false并仅返回现有数据。 当我使用代码示例中的“ queryThatWorks”查询时,此方法可以正常工作。

1 个答案:

答案 0 :(得分:0)

您无需在where子句中使用and运算符。参见findOrCreate

{ where: { teamID: teamID, playerID: req.currentUser.id } }

您可以像这样将数据包含到过滤器中:

{ where: joinTeamsData }

要在return语句中返回特定字段,可以在查询中使用fields选项。

最后,尝试一下:

let data = {
    teamID: teamID,
    playerID: req.currentUser.id,
};

let filter = { where: data };

teamsJoined.findOrCreate(filter, data,
    function(err, instance, created) {
        console.log(instance, created);
    }
);