无法访问对象内部的数据

时间:2019-06-17 12:01:03

标签: node.js nodes typeorm

我正在从数据库中获取特定电子邮件的ID列值。在这种情况下,我要传递email并想获取主键,即id。此操作成功,因为我得到的对象包含具有正确和预期结果的对象。但是我无法访问该对象。

我正在收到这样的物体:

[UserInfo {id:21}]

我无法访问它的ID部分。

我正在使用node.js,用于数据库的postgres和typeorm库来与数据库连接。

    const id = await userRepo.find({
        select:["id"],
        where: {
            email:email
        }
    });

    console.log(id)
   This prints the above object.

我得到的ID是正确的。但是我无法检索对象的ID部分。我尝试了各种方法,例如

id['UserInfo'].id, id.UserInfo

请帮助我访问我收到的对象

2 个答案:

答案 0 :(得分:0)

Typeorm .find()返回一个对象数组,其中包含与您的过滤器相对应的条目,在您的情况下,所有带有email字段的条目与您指定的电子邮件相对应。

因为结果是一个数组,所以您可以通过以下方式访问它:

const records = await userRepo.find({
  select: ['id'],
  where: {
    email,
  },
})
console.log(records[0].id)

您还可以使用.findOne()方法,该方法返回单个元素,在您的情况下可能是更好的解决方法:)

答案 1 :(得分:0)

将字段放入选择部分select:["id"],时,仅在检索数据库的这一部分。
就像您的查询是这样的:select id from userRepo where email = email
并且您需要在选择部分中输入*以检索所有信息:

const id = await userRepo.find({
        select:["*"],
        where: {
            email:email
        }
    });
相关问题