【发布时间】:2021-11-04 03:06:24
【问题描述】:
尽管这个问题已经被问了很多次,但没有一个答案对我有任何帮助。 这是我的猫鼬模式
const mongoose = require('mongoose')
const { Schema } = mongoose;
const recipeSchema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
imagePath: { type: String, required: true },
ingredients:[
{
name:{type:String, required:true},
amount:{type:Number,required:true }
}
]
})
module.exports = mongoose.model("Recipe",recipeSchema);
我需要的是从角度获取数据并使用节点将其存储到我的数据库中
const Recipe = require('../models/recipe.model');
const recipeCtrl={};
recipeCtrl.CreateRecipeServer =async(req, res, next)=>{
if(!req.file) {
return res.status(500).send({ message: 'Upload fail'});
}
else {
let ingredientArray=new Array()
ingredientArray.push(req.body.ingredients)
req.body.imageUrl = 'http://192.168.0.7:3000/images/' + req.file.filename;
const recipe=new Recipe({
name:req.body.name,
description:req.body.description,
imagePath:req.body.imageUrl,
ingredients:[
{
name:ingredientArray,
amount:ingredientArray }
]
});
await recipe.save();
}
除了配料数组之外的所有东西都可以完美/按我的要求工作。
我从 formdata 以数组形式获取成分,因此它必须是 JSON.stringfied 才能附加到表单中。所以我在后端得到的是 string 。例如
**[{"name":"dasdasd","amount":2},{"name":"fsfsd","amount":2},{"name":"sdfsdgd","amount":3}]**
这是一个字符串。关于如何将其转换并存储到数据库的任何想法
【问题讨论】:
-
使用 JSON.parse()
-
当使用 json .parse 这就是我得到的 [ [ { name: 'dasdasd', amount: 2 }, { name: 'fsfsd', amount: 2 }, { name: 'sdfsdgd' , 数量: 3 } ] ]
-
当您使用 json.parse 时,它会转换为 json,因此您需要获取 json 解析的第一个元素,例如
JSON.parse(data)[0]然后插入数据库 -
非常感谢它终于奏效了,3天我就在它后面
-
你想让它回答吗?
标签: node.js arrays json mongodb