不使用array destructuring实现Mongoose数据插入的其他方法
你首次编写的代码无法写入数据库,核心原因是orders.create方法接收的参数中,你传入了{ data, content },这里的data是拆分文件名得到的数组,而你的orders模型的Schema预定义的是no_telp、type、timespan、name、unique_code五个独立字段,不存在名为data的数组字段,字段不匹配导致写入失败。
以下是两种不需要数组解构,仅使用已声明的data变量即可实现正常写入的方案:
方案1:直接通过数组下标取值构造对象
这是最直观的方案,直接按拆分后数组的顺序,把对应下标的值赋值给对应字段即可:
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({ no_telp: data[0], type: data[1], timespan: data[2], name: data[3], unique_code: data[4], content });
注:你提供的第二份可运行代码示例中unique code为笔误,实际应为下划线连接的unique_code
方案2:通过字段映射批量转换为对象
如果后续字段数量增加,手动写下标容易出错,可以通过字段名数组和Object.fromEntries批量构造符合要求的对象:
const data = req.file.originalname.split('.')[0].split('_'); if (data.length < 5) throw new Error('Invalid file name'); // 按数组顺序定义对应的字段名 const orderFields = ['no_telp', 'type', 'timespan', 'name', 'unique_code']; // 批量映射为符合Schema的对象 const orderParams = Object.fromEntries(orderFields.map((field, index) => [field, data[index]])); const content = await fs.readFile(req.file.path, 'utf8'); await orders.create({ ...orderParams, content });
内容的提问来源于stack exchange,提问作者Huda Prikitiew
相关产品推荐
相关产品推荐

