node.js - 拖放后如何更新记录
问题描述
我正在使用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
}
]
解决方案
如果您更新文档,请使用数组中的索引值来更新订单 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
密钥发送到后端之前实际更新前端中已经存在的密钥。这样数组的顺序就无关紧要了。
推荐阅读
- django-viewflow - 表示查看以搜索下一个任务 url
- amazon-web-services - AWS STS 临时凭证 S3 访问被拒绝 PutObject
- snowflake-cloud-data-platform - 有没有人有“最佳实践”与雪花共享单元/集成/回归测试?
- python - 如何在运行文件的同时执行文件?
- python-3.x - 如何在三个要求下聚合数据框?
- microsoft-dynamics - Dynamics HttpClient 调用永远不会成功
- c# - 如何将二维字符串数组传递给点击事件?
- asp.net - 实体框架核心级联删除错误
- php - 我的下拉菜单无法正常工作,我不知道问题所在
- mysql - 更改 JSON 文件中特定工单中的数据