首页 > 解决方案 > 数组解构猫鼬创建

问题描述

有没有其他方法可以在不使用数组解构的情况下将数据插入猫鼬我下面有一些代码,它不起作用,也没有正确插入数据库

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 });

标签: javascriptnode.jsarraysmongodbmongoose

解决方案


你正在做的不是数组解构。数组解构意味着将数据拉出数组。一个示例数组解构可以是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);

推荐阅读