无法使用邮递员通过表单数据将数组发送到mongoDB

时间:2020-05-24 11:10:10

标签: node.js mongodb mongoose postman formidable

我现在正在实现一个api,以将产品添加到数据库中,该产品应包含一个数组字段 tags ,该字段中应包含许多字符串值。在邮递员中,我正在通过表单数据进行发布,因为我在nodejs中使用强大的功能来上传图片。 猫鼬模式示例:

const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema({

Title: {
    type: String,
    required: true,
    maxlength: 32,
},
Description: {
    type: String,
    required: true,
    maxlength: 500,
},
tags: [{
    type: String
}],
Quantity: {
type: Number,
required:true,
},
Price: {
type: Number,
required: true,
},
Picture: {
    data: Buffer,
    pictureType: String,
} }, {timestamps: true} );
module.exports = mongoose.model("Product", ProductSchema);

用于发送产品的代码:

const formidable = require("formidable");
const fileSystem = require("fs");
const Product = require("../models/product")
exports.productController = (req, res)=> {                           

const formidableMethod = new formidable.IncomingForm();

formidableMethod.keepExtensions = true,

formidableMethod.parse(req, (err, fields, files)=> {
    if (err){
        return res.status(400).json({error: "Error during uploading img"})
    } 
    const productSet = new Product(fields); 
    if (files.image){
        productSet.Picture.data = fileSystem.readFileSync(files.Picture.path);
        productSet.Picture.pictureType = files.Picture.type;
    }
    productSet.save((err, output)=>{
        if (err){
            return res.status(400).json({error: "Error saving the product", })
        }
      res.json(output);  
    } )
});

在邮递员中,我正在使用表单数据来发布产品。我尝试了“标签”数组的不同方法。 我已经尝试了正文中的几个 tags 字段,它们的值不同。标签[0],标签[1]和其他方式。 我尝试以不同的方式更改架构中的数组格式,类型为:数组或简单地使用标签:[String]。我现在最好的事情是邮递员会将我的请求添加到数组的第一个元素中,而忽略所有其他请求。 我怀疑这可能是由于我使用了强大的功能,我尝试设置了强大的选项(倍数为true),但也没有运气。我不确定我的问题是邮递员,架构还是强大的问题。 现在,邮递员从表单数据请求返回给我,该请求在正文密钥中包含3个字段(标签)是:

{
    "tags": [
        "value 3"
    ],
    "_id": "5eca55570587f91638280255",
    "Title": "Adding product test",
    "Description": "Description test",
    "Quantity": 10,
    "Price": 49,
}

仅显示值3,忽略值1和值2。任何帮助。

0 个答案:

没有答案