如何查找用户名字字母

How to find user first name letter

我如何找到名字中首字母为首字母的用户,例如我的名字是“Nathan”,当我在搜索输入中输入“n”时,它会显示用户以“n”开头,但不会显示不是的用户以字母“n”开头但包含字母“n”,例如 Henry、Connor..

这是我的 searchController.js:

exports.searchAll = async (req, res) => {
  // Grab query
  const query = req.params.q;

  // Search for user's
  const usersFound = await models.User.findAll({
    where: {
      [Op.or]: [
        {
          fullname: {
            [Op.iLike]: "%" + query + "%",
          },
          // Only include full account users
          passwordhash: {
            [Op.ne]: null, // full account users have a password
          },
          verifiedDT: { [Op.ne]: null },
        },
        {
          institution: {
            [Op.iLike]: "%" + query + "%",
          },
          // Only include full account users
          passwordhash: {
            [Op.ne]: null, // full account users have a password
          },
          verifiedDT: { [Op.ne]: null },
        },
      ],
    },
    attributes: [
      "fullname",
      "public_user_id",
      "institution",
      "location",
      "webpage",
      "linkedin",
      "major",
      "bio",
      "picture",
      "id",
    ],
    include: [
      {
        model: models.Rating,
        attributes: ["skillset_rating", "team_member_rating"],
      },
      {
        model: models.Skill,
        attributes: ["skill"],
      },
    ],
  });

  // Search for teams
  const teamsFound = await models.Team.findAll({
    where: {
      title: {
        [Op.iLike]: "%" + query + "%",
      },
      status: {
        [Op.ne]: "Closed", // past teams
      },
      creatorId: {
        [Op.ne]: null,
      },
    },
    attributes: ["public_team_id", "title", "mission", "status"],
    include: [
      {
        // Creators name
        model: models.User,
        attributes: ["fullname"],
      },
    ],
  });

  // Run searches
  const searchData = await Promise.all([usersFound, teamsFound]);
  res.status(200).json(searchData);
};

这是我的模型 user.js:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
        allowNull: false,
      },
      fullname: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      passwordhash: DataTypes.STRING,
      institution: DataTypes.STRING,
      bio: DataTypes.STRING,
      creator_user_id: DataTypes.UUID,
      public_user_id: DataTypes.STRING,
      picture: DataTypes.STRING(300),
      email: { type: DataTypes.STRING, unique: true },
      gender: DataTypes.STRING,
    },
    {
      tableName: "Users",
      timestamps: true,
      indexes: [
        {
          unique: false,
          fields: ["email", "id", "fullname", "public_user_id"],
        },
      ],
    }
  );

您的查询当前正在寻找 fullname ILIKE '%n%',这意味着字母 n 之前或之后的任意字符组合。如果您只想获得以字母 n 开头的结果,请删除第一个 % 通配符。