UnhandledPromiseRejectionWarning:错误:属性'密码'不存在。 PG-承诺

问题描述 投票:0回答:1

我正在使用pg-promise。

我在尝试插入以下Javascript数组时遇到问题:

[ { email: '[email protected]', password: 'test2' },
  { email: '[email protected]', password: 'test'3 },
  { email: '[email protected]', password: 'test4' },
  { email: '[email protected]', password: 'test5' }]

使用以下内容:

async function insertDB(data){
  const cs = new pgp.helpers.ColumnSet(['email', 'password'], {table: 'users'});
  console.log(data)
  const query = pgp.helpers.insert(data, cs);

  db.none(query)
      .then(data => {
          logger.info(" Query success: ", data);
  })
  .catch(error => {
      logger.warn(" Query error: ", error);
  });
}

我明白了

UnhandledPromiseRejectionWarning:错误:属性'密码'不存在。

**data.password = undefined**
**data[0] = { email: '[email protected]', password: 'test2' }**

如何将此数据插入到postgresdb中?

javascript pg-promise
1个回答
0
投票
// should create columnsets only once:
const cs = new pgp.helpers.ColumnSet(['email', 'password'], {table: 'users'});

function insertDB(data) {

  // wrapping it into a function is safer, for error-reporting via query methods:
  const query = ()=> pgp.helpers.insert(data, cs);

  db.none(query)
      .then(data => {
          // data = null always here, no point displaying it
          logger.info('Query success:', data);
  })
  .catch(error => {
      logger.warn('Query error:', error);
  });
}

在这种情况下,你的功能不需要async

UnhandledPromiseRejectionWarning:错误:属性'密码'不存在。

您正在混淆JavaScript编译器,将该函数声明为async,然后在生成插入时同步抛出错误,因为缺少属性password

如果你想插入一些没有密码的记录,例如null,你可以像这样定义你的列集:

const cs = new pgp.helpers.ColumnSet([
    'email',
    {name: 'password', def: null}
], {table: 'users'});

除此之外,类型ColumnSet最终是灵活的,请参阅每个包含Column的文档。

额外

如果你想使用服务器端DEFAULT值来丢失密码,你可以在Custom Type Formatting的帮助下提供它:

const DEFAULT = {rawType: true, toPostgres: ()=> 'DEFAULT'};

然后你的password列可以像这样定义:

{name: 'password', def: DEFAULT}

还有很多替代方案,init支持modColumn属性。

© www.soinside.com 2019 - 2024. All rights reserved.