我正在使用nodejs和postgresql
我尝试通过ajax调用插入数据。 尝试以下事项。
1. Insert the record in conversation table.
2. get the conversation table last insert id(primary key).
3. last insert id try to insert other table multiple times.
错误:
查询运行良好。在前端插入此数据后不起作用。当我尝试在前端刷新页面时,我在终端" {[错误:此套接字已被对方结束]代码中收到以下错误:' EPIPE&#39 ; }"
我添加了以下代码。
var express = require('express');
var router = express.Router();
var pg = require('pg');
var client = require('../routes/database.js');
var cookieParser = require('cookie-parser');
var dateFormat = require('date-format');
var async = require('async');
var today = dateFormat(new Date());
router.post('/conversation/start', function(req, res) {
//var partyId = sess.userId;
var partyId = 20;
var topic = "welcome";
var msg = "test message";
var to_user_details = JSON.parse([{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]);
client.query('BEGIN', function(err, result) {
if (err) {
console.log(err);
return rollback(client);
}
client.query('insert into conversation (party_id , topic, message, created_on) values (' + "'" + partyId + "'" + ',' + "'" + topic + "'" + ',' + "'" + msg + "'" + ',' + "'" + today + "'" + ') RETURNING id', function(err, result) {
if (err) {
console.log(err);
return rollback(client);
}
var conversationId = result.rows[0].id;
async.each(to_user_details, addToUsersConversation.bind(null, conversationId), function(err) {
if (err) {
console.log(err);
return rollback(client);
}
client.query('COMMIT', client.end.bind(client));
res.send("conversation added");
});
});
});
});
var addToUsersConversation = function(conversationId, toUserDetails, cb) {
client.query('insert into conversation_to (conversation_id , party_id, type) values (' + "'" + conversationId + "'" + ',' + "'" + toUserDetails.id + "'" + ',' + "'" + toUserDetails.type_flag + "'" + ')', function(err, result) {
if (err)
return cb(err);
cb(null);
});
};