【问题标题】:Looking to iterate over JSON in a Sequelize / Postgres DB query to find a matching value希望在 Sequelize / Postgres DB 查询中迭代 JSON 以找到匹配值
【发布时间】:2023-04-06 16:36:01
【问题描述】:

这是我在这里的第一篇文章,所以请温柔。 我在 Node 中使用带有 PostgresDB 的 Sequelize 并尝试使用 findOrCreate 通过电子邮件搜索联系人。电子邮件条目采用 JSON 格式(参见下面的结构)...

我想通过电子邮件查找联系人,并为每个联系人条目遍历 JSON 数组中的每个电子邮件地址。

我在 POST 有效负载中传递了一个电子邮件地址和一个名称。

如果我无法通过电子邮件找到联系人,我想创建一个新联系人(这部分很简单)。

router.post('/gmail/fetchcontact', function (req, res, next){

    Contacts.findOrCreate({
        where: {
          email:  // this is where I am stuck. How do I access this array and loop over?          
        },
        defaults: {
          name: req.body.name // 
        }
      })
      .then(response => {
        if (response[1] === true) {
          console.log('RESPONSE!!!', response[1])
        }

      })

// 这是我希望迭代的 JSON 的结构

[{
          address: 'your.name@gmail.com',
          primary: true,
          rel: 'http://schemas.google.com/g/2005#home'
        },{
          address: 'work@work.com',
          primary: false,
          labels: ['work'],
        },{
          address: 'play@play.com',
          primary: false,
          labels: ['play'],
        }]

有什么想法吗?任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: javascript json node.js postgresql sequelize.js


    【解决方案1】:

    我会创建一个仅包含电子邮件的数组,然后进行 $in 搜索。

    const emails = [{
          address: 'your.name@gmail.com',
          primary: true,
          rel: 'http://schemas.google.com/g/2005#home'
        },{
          address: 'work@work.com',
          primary: false,
          labels: ['work'],
        },{
          address: 'play@play.com',
          primary: false,
          labels: ['play'],
        }].map(email => email.address);
    

    搜索:

    Contacts.findOrCreate({
        where: {
          email: { $in: emails }
        },
        defaults: {
          name: req.body.name // 
        }
      })
      .then(response => {
        if (response[1] === true) {
          console.log('RESPONSE!!!', response[1])
        }
      });
    

    $in 的文档在这里:http://docs.sequelizejs.com/manual/tutorial/models-usage.html#-findall-search-for-multiple-elements-in-the-database

    【讨论】:

    • 非常感谢您的回复。欣赏它。,将尝试代码,如果有效,请回圈...
    【解决方案2】:

    我找到了一个很好的解决方案...

    首先,您必须将数据值更改为类型:Sequelize.JSONB

    然后你可以像这样迭代嵌套的 JSON 对象和数组:

     Contacts.findOne({
        where: {
          email: {
            $contains: [{
              address: req.body.email
            }]
          },
          UserId: req.user.id
        }
      })
    

    ** 请注意,在 $contains 中我将对象包装在一个数组中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2022-12-11
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      相关资源
      最近更新 更多