javascript - 数组解构猫鼬创建
问题描述
有没有其他方法可以在不使用数组解构的情况下将数据插入猫鼬我下面有一些代码,它不起作用,也没有正确插入数据库
const data = req.file.originalname.split('.')[0].split('_');
if (data.length < 5) throw new Error('Invalid file name');
const content = await fs.readFile(req.file.path, 'utf8');
await orders.create({ data, content });
我可以通过使用下面的数组解构来使用此代码来完成这项工作,我想知道是否有任何方法不使用解构,并且只使用像我上面的代码这样的可变数据
const data = req.file.originalname.split('.')[0].split('_');
if (data.length < 5) throw new Error('Invalid file name');
// const [no_telp, type, timespan, name, unique_code] = data;
const content = await fs.readFile(req.file.path, 'utf8');
await orders.create({ no_telp, type, timespan, name, unique code, content });
解决方案
你正在做的不是数组解构。数组解构意味着将数据拉出数组。一个示例数组解构可以是const listCopy = [...list]
或const listAdded = [...list, 12, 48]
。如果您的意思是这部分create({ no_telp, type, timespan, name, unique code, content });
,您正在向 create 方法提供必要的数据。您可以事先创建一个 abject,然后将其发送到 create 方法。const userData = { no_telp, type, timespan, name, unique code, content }; await orders.create(userData);
此外,您要保存的是字符串化数据。读取文件后,fs.readFile()
您必须对其进行解析以正确操作并保存在数据库中。试试这个:
const stringData = await fs.readFile(req.file.path, 'utf8');
const content = JSON.parse(stringData)
console.log(content) // see the data
const userData = {no_telp, type, timespan, name, unique code, content};
await orders.create(userData);
推荐阅读
- javascript - 刷新网页后,我的 blob 值如何变化?
- python - Python - 识别连续 0 组并替换它们
- r - 如何将闪亮的应用程序布局扩展到整个窗口?
- powershell - powershell重新打开子窗体
- pine-script - 图表顶部和底部的颜色
- ruby - 使用 ruby-install 安装 ruby 会导致 Mac M1 上出现错误
- xpath - 是否可以选择 XPATH 节点的属性?
- ios - 多个命令产生颤动 GoogleUtilities
- java - 使用凭证从 java 调用 web 服务
- asp.net - 创建代理服务器 - 转发所有标题、正文、所有内容,但更改 URL