0

I am creating a new user using the following code:

  static async create(user: IUser) : Promise<IUser | undefined> {
    const rows: any = await Pools.execute(
      "INSERT INTO users (email, password, username , admin) VALUES(?,?,?,?)",
      [user.email, user.password, user.username, user.admin]);
    try {
      console.log('created user' , rows[0]);

      if (!rows[0] || !rows[0].length)
        return;
      return;

    } catch (err) {
      throw err;
    }
  }

But the result for console.log('created user' , rows[0]); is:

created user ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 17,
  info: '',
  serverStatus: 2,
  warningStatus: 0
}

Also when I call the function like const createduser = await Users.create(user); the result still is like:

createduser undefined

How can I get the result of new created user back as an IUser object?

best_of_man
  • 643
  • 2
  • 15
  • 1
    Perform a query to retrieve it, like with regular SQL? – robertklep Jan 12 '23 at 07:55
  • @robertklep: Should I create a new query like `const newUser: any = await Pools.execute("SELECT * FROM users WHERE email = ?", [user.email]);` or there is a way to add this new SQL command to previous one? – best_of_man Jan 12 '23 at 08:04
  • 2
    Please don't re-ask the same question. This is a duplicate of [How can I see the result of what I save into the "MySQL" database?](https://stackoverflow.com/questions/75025086/how-can-i-see-the-result-of-what-i-save-into-the-mysql-database). You could start by responding to the questions you were asked there – Phil Jan 12 '23 at 08:05

1 Answers1

0

I found that it seems there is no way to get new created user at a one shot and I should add another query afterwards and change the code like below:

  static async create(user: IUser){
    const rows: any = await Pools.execute(
      "INSERT INTO users (email, password, username , admin) VALUES(?,?,?,?)",
      [user.email, user.password, user.username, user.admin]);
      const newUser: any = await Pools.execute("SELECT * FROM users WHERE email = ?", [user.email]);
    try {
      if (!newUser[0] || !newUser[0].length)
        return;
      return newUser[0][0];

    } catch (err) {
      throw err;
    }
  }
best_of_man
  • 643
  • 2
  • 15