mongodb 如何在拖放后更新记录 您所在的位置:网站首页 mongodb更新多条记录 mongodb 如何在拖放后更新记录

mongodb 如何在拖放后更新记录

2023-03-26 03:27| 来源: 网络整理| 查看: 265

我使用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 } ]


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有