Javascript 如何避免在postgres数据库中插入空值

Javascript 如何避免在postgres数据库中插入空值,javascript,sql,node.js,postgresql,pg-promise,Javascript,Sql,Node.js,Postgresql,Pg Promise,我有一个将数据插入多对多联接表的查询 INSERT INTO playlist_genre(playlist_id, genre_id) VALUES (${playlistId}, ${genre1Id}), (${playlistId}, ${genre2Id}), (${playlistId}, ${genre3Id}) ); 然而,我遇到的问题是,用户不需要genre2Id和genre3Id的值,因此可以是整数或NULL 我试图找到一种方法来编写这个相

我有一个将数据插入多对多联接表的查询

INSERT INTO playlist_genre(playlist_id, genre_id)
VALUES  (${playlistId}, ${genre1Id}),
        (${playlistId}, ${genre2Id}),
        (${playlistId}, ${genre3Id})
);
然而,我遇到的问题是,用户不需要
genre2Id
genre3Id
的值,因此可以是
整数
NULL

我试图找到一种方法来编写这个相同的查询,但它只在存在值时插入。这两列都有
非空
约束

编辑

这是我的播放列表课

class Playlist {
  constructor(playlist) {
    // required fields
    this.title = playlist.title;
    this.playlistType = playlist.playlistType;
    this.userId = playlist.userId;
    this.numberOfTracks = playlist.numberOfTracks;
    this.lengthInSeconds = playlist.lengthInSeconds;
    this.genre1Id = playlist.genre1Id;
    // not required fields
    this.genre2Id = playlist.genre2Id || null;
    this.genre3Id = playlist.genre3Id || null;
    this.description = playlist.description || null;
    this.releaseDate = playlist.releaseDate || null;
  }

  save() {
    return new Promise((resolve, reject) => {
      db.one(sqlCreatePlaylist, this)
        .then((insertedPlaylist) => {
          // Here is where i want to use insertedPlaylist's id 
          // to insert data into 'playlist_genre' table
          resolve(insertedPlaylist);
        })
        .catch(error => reject(error));
    });
  }
以下是sqlCreatePlaylist的外观

INSERT INTO playlists(
  user_id,
  title,
  playlist_type,
  number_of_tracks,
  duration,
  description,
  release_date
)
VALUES(
  ${userId},
  ${title},
  ${playlistType},
  ${numberOfTracks},
  ${lengthInSeconds},
  ${description},
  ${releaseDate}
)
RETURNING *;

要仅插入非空值,请执行以下操作:

insert into playlist_genre (playlist_id, genre_id)
select playlist_id, genre_id
from (values
    (${playlistid}, ${genre1id}),
    (${playlistid}, ${genre2id}),
    (${playlistid}, ${genre3id})
) s (playlist_id, genre_id)
where genre_id is not null

@GordonLinoff,以避免在我的表中加载
NULL
值和不必要的列。直接相关:。这是令人困惑的,因为您接受的答案表明您尝试插入的数据在另一个表中,而您自己的属性变量示例指向在内存中使用数据。作为pg promise的作者,我本打算发表一个正确的答案,但你需要首先澄清这一点。@vitaly-t更新了我的问题以反映你的评论