2017-07-06 95 views
0

这是我的第一篇文章,所以请温和。 我在节点中使用Sequelize w/PostgresDB并尝试使用findOrCreate通过电子邮件搜索联系人。电子邮件条目采用JSON格式(请参阅下面的结构)...想要在Sequelize/Postgres DB查询中遍历JSON以查找匹配值

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

我正在传递邮件有效负载中的电子邮件地址和名称。

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

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: '[email protected]', 
      primary: true, 
      rel: 'http://schemas.google.com/g/2005#home' 
     },{ 
      address: '[email protected]', 
      primary: false, 
      labels: ['work'], 
     },{ 
      address: '[email protected]', 
      primary: false, 
      labels: ['play'], 
     }] 

任何想法?任何帮助将不胜感激。谢谢!

回答

0

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

const emails = [{ 
     address: '[email protected]', 
     primary: true, 
     rel: 'http://schemas.google.com/g/2005#home' 
    },{ 
     address: '[email protected]', 
     primary: false, 
     labels: ['work'], 
    },{ 
     address: '[email protected]', 
     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

+0

谢谢各位大大的答复。欣赏它,会尝试一下代码,并且如果它能够正常工作,就回到原地。 –

0

我发现为这个伟大的解决方案......

首先,你必须改变datavalue键入:Sequelize.JSONB

然后你可以iter吃了嵌套的JSON对象和数组,像这样:

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

**请注意,在$包含我包裹对象数组