【问题标题】:How to add insert objects by id如何通过 id 添加插入对象
【发布时间】:2020-02-01 21:14:52
【问题描述】:

所以我使用 NodeJS 将数据从我的 React 应用程序发送到我的 PostgreSQL 数据库

ReactJS

let data = files.map(( { name }, index, album_id ) => ({ name, index : index, album_id: 
params.albumId }));

    let request = new Request(`http://localhost:3000/albums/${params.albumId}/songs`, {
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(data),
    });

     fetch(request)
      .then((response) =>
        response.json())
          .then((data) => {
          })
          .catch((error) => {
            console.log(error)
          })

NodeJS - 查询.js

const addSong = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, link, index, album_id } = request.body;

for (var i = 0; i < request.body.length; i++) {
  pool.query('INSERT INTO songs (name, link, index, album_id) VALUES ($1, $2, $3, $4) ON 
  CONFLICT (index) DO NOTHING RETURNING *', [request.body[i].name, request.body[i].link, 
  request.body[i].index, request.body[i].album_id], (error, results) => {
    if (error) {
     throw error
     console.log(error)
     } else {
       console.log("addSong " + JSON.stringify(results.rows) + id);

   }
  });
 }
}

NodeJS - index.js

const app = express();
const db = require('./queries');

app.post('/albums/:id/songs', db.addSong)

索引约束是一个唯一约束,表示如果索引具有相同的值,则不能多次添加索引。我的问题是即使album_id 不同,也会在每个对象上设置约束,但我希望每个页面都能够有单独的索引约束。

这是我的 GET 请求中我的 json 的样子:

我的问题是如何在我的 POST 请求中的代码中添加一些内容,例如 INSERT WHERE album_id = id,其中 id 是 parseInt(request.params.id)

【问题讨论】:

  • 我不确定你在问什么。 id 是专辑 ID,它也在您的每个对象中,对吗?您是否收到 postgresql 错误?您是否只想忽略发布的与您调用的路线中指定的专辑 ID 不同的歌曲?那就是let matchedSongs = request.body.filter(x =&gt; x.album_id === parseInt(request.params.id)); 对吧?
  • @JasonGoemaat 抱歉,我对 Node 有点陌生。我会把它放在我的代码的什么地方?
  • 对不起,我还没有从节点使用 postgresql。我看到查询使用回调,因此您希望在发送响应之前等待所有回调完成...这可能应该是您问题的重点或单独的问题...
  • @JasonGoemaat 它不允许我发送响应,因为它说“在发送到客户端后无法设置标题”。不过我喜欢你的代码。我只是好奇我应该在我的代码中的什么位置以及如何实现它?
  • 最后一个回调返回后,您需要某种方式来发送响应。现在我认为您对query() 进行了所有调用并且函数完成了,但尚未调用回调。我会尝试使用 Promise 版本和 pomise.all(xxx).then(() =&gt; sendResponse()) 等待所有这些都完成并发送响应...

标签: node.js reactjs postgresql


【解决方案1】:

试试这个方法

/// 从 npm 导入异步模块

function insertData(item,callback) {
    const { name, link, index, album_id } = item;
    client.query('INSERT INTO songs (name, link, index, album_id) VALUES ($1,$2,$3,$4)', [
        name, link, index, album_id
         ], 
    function(err,result) {
      // return any err to async.each iterator
     if(err)
      return callback(err);

      console.log("addSong " + JSON.stringify(results.rows) + id);
        callback(err, result);
    })
  }
  const addSong = (request, response) => {
  async.each(request.body,insertData,(err) => {
    // Release the client to the pg module
    done();
    if (err) {
      return console.error('error running query', err);
    }
   // callback here
  });
}

并且供您参考 Bulk insert into Postgres with brianc/node-postgres

Multi-row insert with pg-promise

【讨论】:

  • 谢谢,但它是如何做到的,所以索引约束不会在每个对象上运行相同。因为我希望通过 id 或其他方式运行请求,以便每个页面的行为都不同,因为在我的前端我通过专辑 id 获取数据
猜你喜欢
  • 2019-10-01
  • 2017-03-09
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多