首页 > 解决方案 > 拖放后如何更新记录

问题描述

我正在使用react-sortable-hoc拖放和重新排序项目。当我这样做时,虽然我想更新数据库(node.js 和 mongodb)。

首先,我已将其更改为功能组件,这就是为什么我的语法看起来与示例有点不同的原因。

const onSortEnd = ({ oldIndex, newIndex }) => {

    setItems((items) => arrayMove(items, oldIndex, newIndex));

    const newArray = arrayMove(items, oldIndex, newIndex);

    async function makePatchRequest() {
      const config = {
        method: "patch",
        url: "http://localhost:8000/api/admin/faq/order",
        headers: { Authorization: "Bearer " + auth.token },
        data: {
          order: newArray,
        },
      };

      let res = await axios(config, { order: newArray });

    }
    makePatchRequest();
  };

我将新数组发送到后端,拖放后的所有内容都按顺序发送。问题是我真的不知道如何在后端处理它。我是否需要删除所有记录,然后遍历数组并插入新记录?我最初想遍历记录并更新它们,但它实际上并没有做任何事情,可能是因为代码错误或我的逻辑错误,因为它所做的只是用完全相同的数据覆盖,因为所有改变的是数组的顺序,而不是数组中的实际 id 或 _id。

exports.faqSort = async (req, res) => {
  const { order } = req.body;
  console.log(order);

  await order.map((o) => {
    Faq.update({ _id: o._id }, { $set: { id: o.id } });
  });
};

这是页面加载时的数组:

[
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    id: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    id: 2,
    __v: 0
  },
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    id: 3,
    __v: 0
  }
]

这是我发送到后端的新数组

[
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    order: 3,
    __v: 0
  },
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    order: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    order: 2,
    __v: 0
  }
]

标签: node.jsreactjsmongodbmongoose

解决方案


如果您更新文档,请使用数组中的索引值来更新订单 ID。

const promises = order.map( async (o, index) => {

  let orderkey = index + 1;
  const promise = Faq.updateOne({ _id: o._id }, { $set: { order: orderkey } });

  return promise;

});

const results = await Promise.all(promises);

这样,order密钥将根据您发送的数组的顺序进行更新。

但是请考虑在将order密钥发送到后端之前实际更新前端中已经存在的密钥。这样数组的顺序就无关紧要了。


推荐阅读