首页 > 解决方案 > 如何使用node js将多个字段同时添加到sql数据库中

问题描述

我正在编写一个函数,它需要一个对象和一个用户 ID 将数据插入一个名为 userdetails 的表中,如果字段不为空,则应更新这些字段,是否有任何简短的方法来编写 sql 查询。我正在使用 mysql 进行数据库连接。

class UserDetails {
  constructor(options) {
    this.setFields(options);
  }

  setFields(options) {
    this.id = options.id || null;
    this.userId = options.userId || null;
    this.firstName = options.firstName || null;
    this.lastName = options.lastName || null;
    this.location = options.location || null;
    this.interests = options.interests || null;
    this.avatar = options.avatar || null;
  }

  /**
   * Update the details of the user
   * @param {Number} userId ID of the user
   * @param {Object} fields Contains the fields of the data to be updated
   */
  async updateDetails(userId, fields) {
    this.userId = userId;
    const fieldNames = ['id','firstName','lastName','location','interests','avatar'];

    const {id,firstName,lastName,location,interests,avatar} = fields;

    // do something

  }
}

标签: mysqlnode.jsexpress

解决方案


推荐阅读