Task: Get the id of the added record as in php, through mysql_insert_id () and return it back to the client.


Customer:

// В начале переменные с данными о пользователе var ... ; //Создание блока с сообщением и показ на странице function msg(avatar, nick, text, my){ // В m нужно добавить получаемый id сообщения var m = ... ; messages .append(m) } //Получение ответа и отправка данных в функцию socket.on(dialog, function (data) { msg( data.avatar, data.name, data.text, data.my, data.id ); }); //Отправка на сервер socket.emit("chat", { id: dialog, my: my_id text: text, name: name, avatar: avatar, }); 

Server:

 client.on('chat', function (chat) { try { //Получаемые данные пользователя var post = { dialog: chat.id, text: chat.text, users: chat.my, status: 1, date: new Date() }; //Отправка сообщения в базу данных var query = connection.query( 'INSERT INTO chat SET ?', post, function(err, result) { console.log('Добавлено сообщение'); }); //Отправка сообщения обратно на страницу client.emit(chat.id, chat); //Здесь нужно отправить id сообщения client.broadcast.emit(chat.id, chat); } catch (e) { console.log(e); client.disconnect(); connection.end(); } }); 

    1 answer 1

    If the chat table has a unique id with AUTO_INCREMENT , then after adding, insertId should be available to insertId .

     //Отправка сообщения в базу данных var query = connection.query( 'INSERT INTO chat SET ?', post, function(err, result) { console.log('Добавлено сообщение с id = ' + result.insertId); }); 

    Documentation .

    • And do not tell me how then attach this id to the user data sent back? That is, it turns out the chat array to add another entry with the name id_chat = result.insertId ... - Albert Ushakov
    • I mean exactly how this variable is then thrown into the chat array? - Albert Ushakov
    • @Albert Ushakov as an option, emit and broadcast transfer to callback connection.query for synchronicity. After the request in the database passes - chat.id = result.insertId , your emit and broadcast . - mix
    • Ahh that's how it is. Thank. - Albert Ushakov
    • Hmm, I do this ... var query = connection.query ('INSERT INTO chat_m13 SET?', Post, function (err, result) {console.log ('Added message'); chat.id_chat = result.insertId; client. emit (chat.id, chat); client.broadcast.emit (chat.id, chat);}); ... does not work. - Albert Ushakov