Node.js 如何发布多个阵列节点

Node.js 如何发布多个阵列节点,node.js,arrays,mongodb,express,mongoose,Node.js,Arrays,Mongodb,Express,Mongoose,我需要同时发布多个数组,,以便实现以下目标: { name:"John Snow", detail: [ {size: "M", total: 5, color: "red"}, {size: "S", total: 2, color: "black"} ] } 我使用的动态表单可以为细节数组生成新的输入字段。这就是我的模式模型: const OrderSchema = n

我需要同时发布多个数组,以便实现以下目标:

{
 name:"John Snow",
 detail: [
    {size: "M", total: 5, color: "red"},
    {size: "S", total: 2, color: "black"}
 ]
}
我使用的动态表单可以为细节数组生成新的输入字段。这就是我的模式模型:

const OrderSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    detail:[{
        size:{},
        color:{},
        total:{}
    }],
    date:{
        type: Date,
        default: Date.now
    }
});
这是我的路标:

router.post('/add', (req, res) => {
    let errors = [];

    if (!req.body.name) {
        errors.push({ text: 'Your customer name is empty' });
    }
    if (errors.length > 0) {
        res.render('orders/add', {
            errors: errors,
            customer: req.body.name,
            detail:[{
                size: req.body.size,
                color: req.body.color,
                total: req.body.total
            }]
        });
    } else {
        const newUser = {
            customer: req.body.name,
            detail:[{
                size: req.body.size,
                color: req.body.color,
                total: req.body.total
        }
        new Order(newUser)
            .save()
            .then(order => {
                res.redirect('/');
            })
    }
});
提交帖子是工作,只是结果不是我想要的:

{
 name:"John Snow",
 detail: [
    {size: ["M","S"], total: [5,2], color: ["red", "black"]}
 ]
}

我希望你能帮助我,谢谢

假设您在
请求正文中有详细信息

req.body.details
如下所示:

 details: [
    {size: "M", total: 5, color: "red"},
    {size: "S", total: 2, color: "black"}
 ]
然后,您可以这样简单地保存它:

detail: req.body.details

请注意,您的详细信息模式有点奇怪:

detail:[{
    size:{}, // seems to be a string not an object
    color:{}, // seems to be a string not an object
    total:{} // seems to be a number not an object
}]
相反,我认为你可以:

detail:[{
   size:{type: String},
   color:{type: String}, 
   total:{type: Number} 
}]

编辑:

因为您似乎没有验证细节,所以您可以简单地将其作为模式中的一个数组(这取决于您和最有效的方法)

一般来说,
req.body.details
可能来自您提出请求的任何地方。它可以被排序并等于要保存在数据库中的数组


例如,我不完全了解
req.body.size
中的内容,但如果它是一个数组,如
[“M”,“S”]
,则您将提取每个元素并创建单独的对象,然后将其推送到要保存在数据库中的数组中

看看下面:

let size=[“M”,“S”]
设总数=[5,2]
让颜色=[“红色”、“黑色”]
让detailsToDb=[]

对于(设i=0;要求同时发布多个数组,或者您可以传递一个包含所有详细对象的数组吗?是的,因为此表单用于客户发票。客户可以选择所有大小选项(S M L XL XXL XXXL)在一个事务/输入hanks中,您能告诉我如何获取req.body.details吗?因为没有输入具有该名称属性。对于架构,如果我输入字符串类型,它将向我发送错误“值转换为字符串失败”因为我同时提交了多个数组。当然,我编辑了答案。看一看。有了这个,我相信你仍然可以保持对类型的验证。
detail: { type: Array }