fileLink не разрешен схемой

Я пытаюсь использовать Simple Schema в своем текущем проекте Meteor React, но по какой-то причине я не могу заставить его работать.

Это моя схема:

Comments.schema = new SimpleSchema({
  city: {
    type: String,
    label: 'The name of the city.'
  },

  person: {
    type: String,
    label: 'The name of the person.'
  },
  location: {
    type: String,
    label: 'The name of the location.'
  },
  title: {
    type: String,
    label: 'The title of the comment.'
  },

  content: {
  type: String,
  label: 'The content of the comment.'
  },

  fileLink: {
  type: String,
  regEx: SimpleSchema.RegEx.Url,
  label: 'The url of the file.'
  },

  createdBy: {
  type: String,
  autoValue: function(){ return this.userId },
  label: 'The id of the user.'
  }
});

А это моя вставка:

  createSpark(event){
    event.preventDefault();

    const city = this.city.value;
    const person = this.person.value;
    const location = this.location.value;
    const title = this.title.value;
    const content = this.content.value;
    const fileLink = s3Url;

    insertComment.call({
      city, person, location, title, content, fileLink
      }, (error) => {
        if (error) {
              Bert.alert(error.reason, 'danger');
          } else {
              target.value = '';
              Bert.alert('Comment added!', 'success');
          }
      });
    }

Я сохраняю значение, полученное от amazon, в глобальной переменной с именем s3Url. Я могу без проблем записать эту переменную в console.log, но когда я хочу записать ее в базу данных, я получаю сообщение об ошибке «fileLink не разрешено схемой».

Кто-нибудь видит, что я делаю неправильно?

Вот мой файл comments.js:

import faker from 'faker';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Factory } from 'meteor/dburles:factory';

export const Comments = new Mongo.Collection('comments');

Comments.allow({
  insert: () => false,
  update: () => false,
  remove: () => false,
});

Comments.deny({
  insert: () => true,
  update: () => true,
  remove: () => true,
});

Comments.schema = new SimpleSchema({
  city: {
    type: String,
    label: 'The name of the city.'
  },

  person: {
    type: String,
    label: 'The name of the person.'
  },
  location: {
    type: String,
    label: 'The name of the location.'
  },
  title: {
    type: String,
    label: 'The title of the comment.'
  },

  content: {
    type: String,
    label: 'The content of the comment.'
  },

  fileLink: {
    type: String,
    regEx: SimpleSchema.RegEx.Url,
    label: 'The url of the file.'
  },

  createdBy: {
    type: String,
    autoValue: function(){ return this.userId },
    label: 'The id of the user.'
  }
});

Comments.attachSchema(Comments.schema);

И мой файл method.js:

import { Comments } from './comments';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { rateLimit } from '../../modules/rate-limit.js';

export const insertComment = new ValidatedMethod({
  name: 'comments.insert',
  validate: new SimpleSchema({
    city: { type: String },
    person: { type: String, optional: true },
    location: { type: String, optional: true},
    title: { type: String },
    content: { type: String },
    fileLink: { type: String, regEx: SimpleSchema.RegEx.Url },
    createdBy: { type: String, optional: true }
  }).validator(),
  run(comment) {
    Comments.insert(comment);
  },
});

rateLimit({
  methods: [
    insertComment,

  ],
  limit: 5,
  timeRange: 1000,
});

Немного поработав над этим, я заметил некоторые вещи, которые я делал неправильно. 1. У меня не было правильного значения для моей простой схемы. 2. Некоторые проблемы связаны с тем, что в URL-адресе есть пробелы. Что я могу сделать, чтобы исправить это? 3. Текущая ошибка, которую я получаю: «Исключение при доставке результата вызова 'comments.insert': ReferenceError: цель не определена».


person Deelux    schedule 10.11.2016    source источник
comment
Является ли s3Url полным URL-адресом или относительным путем? Можете ли вы показать вывод вашего console.log()? Также можете показать код в insertComment.call()?   -  person Michel Floyd    schedule 10.11.2016
comment
@MichelFloyd спасибо за быстрый ответ. Я продолжил работу над этим и обновил этот пост. Это все еще не работает на 100%, но, по крайней мере, теперь я получаю другую ошибку. Я думаю, что некоторые проблемы также связаны с тем, что URL-адрес содержит пробелы. Есть ли способ исправить это?   -  person Deelux    schedule 12.11.2016
comment
Это URL-адрес, который я храню в s3Url: ec2016.s3-eu -central-1.amazonaws.com/undefined/test.png Но когда имя файла содержит пробелы, это тоже не работает.   -  person Deelux    schedule 12.11.2016
comment
Amazon никогда не должен давать вам имя с пробелами. Также что это за " в конце вашего URL. Это выглядит неправильно. Наконец, ваш URL, вероятно, нуждается в префиксе http:// или https:// для передачи RegEx.url.   -  person Michel Floyd    schedule 13.11.2016
comment
Исключение при доставке результата вызова 'comments.insert': ReferenceError: цель не определена это очевидно, потому что вы не объявляете переменную target. Я предполагаю, что вы пытаетесь очистить элемент формы после отправки, это будет сделано event.target.reset   -  person kkkkkkk    schedule 15.11.2016
comment
Большое спасибо, ребята. Это действительно имело отношение к целевой переменной, которая не была определена. Меня это смутило, потому что я совершенно забыл об этой переменной. Я думал, что речь идет о чем-то другом. Еще раз спасибо, что нашли время ответить.   -  person Deelux    schedule 20.11.2016
comment
Мне также удалось отформатировать URL-адрес, как я хотел, используя: encodeURI(s3Url)   -  person Deelux    schedule 20.11.2016


Ответы (1)


Немного поработав над этим, я заметил некоторые вещи, которые я делал неправильно. 1. У меня не было правильного значения для моей простой схемы. 2. Некоторые проблемы связаны с тем, что в URL-адресе есть пробелы. Что я могу сделать, чтобы исправить это? 3. Текущая ошибка, которую я получаю: «Исключение при доставке результата вызова 'comments.insert': ReferenceError: цель не определена».

Спасибо @Khang

person Deelux    schedule 29.11.2016