【问题标题】:Sequelize find or create for list of itemsSequelize 查找或创建项目列表
【发布时间】:2020-04-30 05:41:14
【问题描述】:

我是续集的新手,看不懂,但没有找到任何具体的东西

// API Method
function SeederApi(req: Request, res: Response) {
  let request = req.body;
  let _model_methods = new ModelMethod();
  request.forEach((obj: any) => {
    const condition = { name: obj.username };
    const value = {
      name: obj.username ,
      short_text: obj.short_txt
    };
    _model_methods.findorCreate(condition, value)
      .then((resp: any) => {
        const _response = resp.get({ plain: true });
        console.log(_response);
      });
  });
    return res.status(200).send("Created");
}
export class ModelMethod{

  init(){}

  findorCreate = (condition: any, value: any) => {
    return Model
      .findOne({ where: condition })
      .then((obj : any) => {
        if(obj){ return obj }
        return RiskFactors.create(value);
      })
  }
}

这里的问题是当列表中有 2 个或更多具有相同用户名的条目时,它应该返回 obj 而不是创建一个。如果请求中只有一项,则 IT 可以正常工作。但是当我有多个可能具有相同用户名的项目时。它最终会创建重复的条目,因为 sequelize 查询是异步的,但我的循环不是。

我了解这里的问题,我不知道如何处理它。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript node.js typescript sequelize.js


    【解决方案1】:

    不要在迭代中将 forEach 与异步调用一起使用。 使用通常的 for:

    for (const obj:any of request) {
      const condition = { name: obj.username };
      const value = {
        name: obj.username ,
        short_text: obj.short_txt
      };
      const resp = await _model_methods.findorCreate(condition, value);
      const _response = resp.get({ plain: true });
      console.log(_response);
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2014-08-10
      • 2013-08-20
      • 2020-01-20
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      相关资源
      最近更新 更多