0

我最近开始从事一个项目,在该项目中,管理员可以通过填写表格来在线创建游览。通过填写表格,将引入的信息介绍 Mongoose Schema 并创建 JSON。

在 createcontent.js 文件中,我使用了表单中的数据, new FormData();因为要上传图像,我使用了一个名为multer的模块。

const createTour_form = document.querySelector('.form-create__tour');
if (createTour_form) {
    createTour_form.addEventListener('submit', (cr) => {
        cr.preventDefault();

        const create = new FormData();
        // Name
        create.append('name', document.getElementById('tour_name').value);
        //Tour Duration
        create.append('duration', document.getElementById('tour_duration').value);
        //Number Participoants
        create.append('maxGroupSize', document.getElementById('tour_participants').value);
        //Tour Difficulty
        create.append('difficulty', document.getElementById('tour_difficulty').value);
        //Tour Price
        create.append('price', document.getElementById('tour_prices').value);
        //Short Description
        create.append('summary', document.getElementById('tour_short_des').value);
        //Description
        create.append('description', document.getElementById('tour_long_des').value);

        createTour(create);
    })
}

我使用模块slugify将游览名称转换为我在 url 中使用的 slug。这是我的猫鼬模式:

const tourchema = new mongoose.Schema({
    name: {
        type: String,
        require: [true, 'A tour mush have a name'],
        unique: true,
        trim: true,
        maxlength: [50, 'A tour name must have less or equal then 50 characters'],
        minlength: [10, 'A tour name must have more or equal then 10 characters'],
        //validate:[validator.isAlpha, 'Tour name must only contain characters']
    },
    slug: {
        formType: String
    },
    duration: {
        type: Number,
        require: [true, 'A tour must have a duration']
    },
    maxGroupSize: {
        type: Number,
        require: [true, 'A tour must have a group size']
    },
    difficulty: {
        type: String,
        require: [true, 'A tour must have a difficulty'],
        enum: {
            values: ['easy', 'medium', 'difficult'],
            message: 'Difficulty is either: easy, medium, difficult'
        }
    },
    ratingsAverage: {
        type: Number,
        default: 4.5,
        min: [1, 'Raiting must be above 1.0'],
        max: [5, 'Raiting must be below 5.0'],
        set: val => Math.round(val * 10) / 10
    },
    ratingsQuantity: {
        type: Number,
        default: 0
    },
    price: {
        type: Number,
        require: [true, 'A tour must have a price']
    },
    priceDiscount: {
        type: Number,
        validate: {
            validator: function (val) {
                //his only points to create doc on new document creation
                return val < this.price;
            },
            message: 'Discount price ({VALUE}) shoud be below the regular price'
        }
    },
    summary: {
        type: String,
        trim: true,
        require: [true, 'A tour must have a description']
    },
    description: {
        type: String,
        trim: true
    },
    imageCover: {
        type: String,
        require: [true, 'A tour must have a cover image']
    },
    images: [String],
    createdAt: {
        type: Date,
        default: Date.now()

    },
    startDates: [Date],
    secretTour: {
        type: Boolean,
        default: false
    },
    startLocation: {
        //GeoJSON
        type: {
            formType: String,
            default: 'Point',
            enum: ['Point']
        },
        coordinates: [Number],
        adress: String,
        description: String
    },
    locations: [
        {
            type: {
                type: String,
                default: 'Point',
                enum: ['Point']

            },
            coordinates: [Number],
            adress: String,
            description: String,
            day: Number
        }
    ],
    // guides:Array
    guides: [
        {
            type: mongoose.Schema.ObjectId,
            ref: 'User'
        }
    ]
}

tourchema.index({ slug: 1 });
tourchema.pre('save', function (next) {
    this.slug = slugify(this.name, { lower: true });
    next();
});

当我从表单 unsign axios winth 异步函数上传数据时:

import axios from 'axios';
import { showAlert } from './alert';

export const createTour = async(data)=>{
  try{
     const create_tour = await axios({
          method:'POST',
          url:'http://127.0.0.1:3000/api/v1/tours',
          data:data
     });
  }
  catch(err){
       console.log(err);
       showAlert('error',err.response.data.message); 
  }
}

当推荐操作发生时,会发生错误 slugify: string argument expected 我在互联网上没有找到任何关于此错误的信息。我尝试构建自己的功能来替换模块,但它没有工作没有解决这个错误的解决方案??

4

1 回答 1

0

您可以将“FormData”转换为对象,然后解析它

function formDataToObj(formData) {
    let obj = {};
    for (let key of formData.keys()) {
        obj[key] = formData.get(key)
    }
    return obj;
}

例子:

function formDataToObj(formData) {
  let obj = {};
  for (let key of formData.keys()) {
    obj[key] = formData.get(key)
  }
  return obj;
}
    

const fd = new FormData()
fd.append('a', 1)
fd.append('b', 2)
const obj = formDataToObj(fd)
console.log( obj )
const json = JSON.stringify( obj )
console.log( json )

于 2020-07-20T23:07:14.137 回答