it('extending a schema with a selector after attaching it, collection2 validation respects the extension', (done) => {
    const schema = new SimpleSchema({
      foo: String
    });

    const collection = new Mongo.Collection('ExtendAfterAttach2');
    collection.attachSchema(schema, { selector: { foo: "foo" } });

    collection.insert({
      foo: "foo",
      bar: "bar"
    }, {
      filter: false
    }, (error) => {
      expect(error.invalidKeys[0].name).toBe('bar');

      schema.extend({
        bar: String
      });

      collection.insert({
        foo: "foo",
        bar: "bar"
      }, {
        filter: false
      }, (error2) => {
        expect(!!error2).toBe(false);

        done();
      });
    });
  });
    it('upsert runs autoValue only once', function (done) {
      const upsertAutoValueTest = new Mongo.Collection('upsertAutoValueTest');
      let times = 0;

      upsertAutoValueTest.attachSchema(new SimpleSchema({
        foo: {
          type: String
        },
        av: {
          type: String,
          autoValue() {
            times++;
            return "test";
          }
        }
      }));

      upsertAutoValueTest.remove({});

      upsertAutoValueTest.upsert({
        foo: 'bar'
      }, {
        $set: {
          av: 'abc'
        }
      }, (error, result) => {
        expect(times).toBe(1);
        done();
      });
    });
  it('attach and get simpleSchema for local collection', function () {
    var mc = new Mongo.Collection(null);

    mc.attachSchema(new SimpleSchema({
      foo: {type: String}
    }));

    expect(mc.simpleSchema() instanceof SimpleSchema).toBe(true);
  });
  it('empty strings are removed but we can override', function (done) {
    const RESSchema = new SimpleSchema({
      foo: { type: String },
      bar: { type: String, optional: true }
    });

    const RES = new Mongo.Collection('RES');
    RES.attachSchema(RESSchema);

    // Remove empty strings (default)
    RES.insert({
      foo: "foo",
      bar: ""
    }, (error, newId1) => {
      expect(!!error).toBe(false);
      expect(typeof newId1).toBe('string');

      const doc = RES.findOne(newId1);
      expect(doc instanceof Object).toBe(true);
      expect(doc.bar).toBe(undefined);

      // Don't remove empty strings
      RES.insert({
        foo: "foo",
        bar: ""
      }, {
        removeEmptyStrings: false
      }, (error, newId2) => {
        expect(!!error).toBe(false);
        expect(typeof newId2).toBe('string');

        const doc = RES.findOne(newId2);
        expect(doc instanceof Object).toBe(true);
        expect(doc.bar).toBe('');

        // Don't remove empty strings for an update either
        RES.update({
          _id: newId1
        }, {
          $set: {
            bar: ''
          }
        }, {
          removeEmptyStrings: false
        }, (error, result) => {
          expect(!!error).toBe(false);
          expect(result).toBe(1);

          const doc = RES.findOne(newId1);
          expect(doc instanceof Object).toBe(true);
          expect(doc.bar).toBe('');
          done();
        });
      });
    });
  });
  it('handles prototype-less objects', function (done) {
      const prototypelessTest = new Mongo.Collection('prototypelessTest');

      prototypelessTest.attachSchema(new SimpleSchema({
        foo: {
          type: String
        }
      }));

      const prototypelessObject = Object.create(null);
      prototypelessObject.foo = 'bar'

      prototypelessTest.insert(prototypelessObject, (error, newId) => {
        expect(!!error).toBe(false);
        done();
      });
    });
Example #6
0
import { Mongo } from 'meteor/mongo';

import { NonConformitiesSchema } from '../schemas/non-conformities-schema.js';
import { CollectionNames } from '../constants.js';
import { WorkItems } from './work-items.js';
import { Standards } from './standards';


const NonConformities = new Mongo.Collection(CollectionNames.NCS);
NonConformities.attachSchema(NonConformitiesSchema);


NonConformities.helpers({
  isAnalysisCompleted() {
    const { status, completedAt, completedBy } = this.analysis || {};
    return (status === 1) && completedAt && completedBy;
  },
  areStandardsUpdated() {
    const { status, completedAt, completedBy } = this.updateOfStandards || {};
    return (status === 1) && completedAt && completedBy;
  },
  getLinkedStandards() {
    return Standards.find({ _id: { $in: this.standardsIds } }).fetch();
  },
  deleted() {
    const { isDeleted, deletedAt, deletedBy } = this;
    return (isDeleted === true) && deletedAt && deletedBy;
  },
  getWorkItems() {
    return WorkItems.find({ 'linkedDoc._id': this._id }).fetch();
  },
Example #7
0
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';



export const Pins = new Mongo.Collection('Pins');

Pins.deny({
    insert(){ return true; },
    update(){ return true; },
    remove(){ return true; },
});

Pins.schema = new SimpleSchema({
    _id: { type: String, regEx: SimpleSchema.RegEx.Id},
    title: { type: String },
    createdAt: { type: Date,  denyUpdate: true },
    userId: { type: String, regEx: SimpleSchema.RegEx.Id, optional: true },
    url: { type: String, regEx: SimpleSchema.RegEx.Url },
});

Pins.publicFields = {
    title: 1,
    createdAt: 1,
    url: 1,
    userId: 1,
};

//"meteor add aldeed:collection2" required
Pins.attachSchema(Pins.schema);
Example #8
0
import { Mongo } from 'meteor/mongo';
import Constants from '../lib/constants.js';
 
var Schemas = {};

Schemas.Resource = new SimpleSchema({
  description: {
    type: String,
    label: "Descripción",
    max: 200,
    index: "text"
  },
  quantity: {
    type: Number,
    label: "Cantidad"
  },
  category: {
    type: Number,
    label: "Categoría",
    allowedValues: Object.keys(Constants.resource_categories)
                         .map((key) => { return parseInt(key); }),
  }
});

const Resources = new Mongo.Collection('resources');
Resources.attachSchema(Schemas.Resource);

export default Resources;
Example #9
0
import { Mongo } from 'meteor/mongo';
import { chartsSchema, dashboardsSchema, chartsLocationsSchema } from './schemas/';

const Charts = new Mongo.Collection('charts');
const Dashboards = new Mongo.Collection('dashboards');
const ChartsLocations = new Mongo.Collection('chartsLocations');

Dashboards.attachSchema(dashboardsSchema);
ChartsLocations.attachSchema(chartsLocationsSchema);
// Charts.attachSchema(chartsSchema);  // TODO Oleg: add Charts Schema

export { Charts, Dashboards, ChartsLocations };
		type: String,
		label: 'Acct Status, Active means is on air',
 		allowedValues   : ["Active", "Suspended"],
		defaultValue    : "Active"
	},
	timestamp: {
		type: Date,
		label: 'Latest Timestamp',
		autoValue : function(){
			return new Date();
		},
	},

});

Acct.attachSchema(Acct.schema);

Acct.publicFields = {
  _id 			: 1,
  name 			: 1,
  ownerId 	: 1,
  saldo 		: 1,
  currency 	: 1,
  timestamp : 1,
};

Acct.helpers({
	owner() {
		return Member.findOne(this.ownerId);
	},
});
Example #11
0
Items.schema = new SimpleSchema({
  createdAt: {
    type: Date,
  },
  text: {
    type: String,
    max: 500,
  },
  isChecked: {
    optional: true,
    type: Boolean,
  },
});

Items.attachSchema(Items.schema);

const insert = new ValidatedMethod({
  name: 'items.insert',
  validate: new SimpleSchema({
    text: { type: String },
  }).validator(),
  run({ text }) {
    Items.insert({
      createdAt: new Date(),
      text,
      isChecked: false,
    });
  },
});
Example #12
0
    type: String,
    label: "Country code"
  },
  createdAt: {
    type: Date,
    autoValue() {
      if(this.isInsert){
        return new Date();
      } else {
        this.unset();
      }
    }
  }
});

Cities.attachSchema(CitySchema);

Cities.publicFields = {
	name: true,
};

Cities.deny({
	insert() {
		return true;
	},
	update() {
		return true;
	},
	remove() {
		return true;
	}
Example #13
0
import { Mongo } from 'meteor/mongo';

import { MilestoneSchema } from '../schemas';
import { CollectionNames } from '../constants';

const Milestones = new Mongo.Collection(CollectionNames.MILESTONES);

Milestones.attachSchema(MilestoneSchema);

export { Milestones };
Example #14
0
Blogs.attachSchema(new SimpleSchema({
  title: {
    type: String,
    max: 50
  },
  preview: {
    type: String,
    max: 100,
    autoValue: function() {
      if(this.field('content').isSet) {
        return this.field('content').value;
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    optional: true
  },
  content: {
    type: String,
    max: 2000
  },
  tag: {
    type: String,
    defaultValue: 'none'
  },
  createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    optional: true
  },
  // Force value to be current date (on server) upon update
  // and don't allow it to be set upon insert.
  updatedAt: {
    type: Date,
    autoValue: function() {
      if (this.isUpdate) {
        return new Date();
      }
    },
    denyInsert: true,
    optional: true
  }
}));
});

TaskSchema = new SimpleSchema({
  taskText: {
    type: String
  },
  completed:{
    type: Boolean
  },
  createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      }
    }
  },
  author: {
    type: String,
    autoValue: function() {
      if (this.isInsert) {
        return this.userId;
      }
    }
  }
});

Tasks.attachSchema(TaskSchema)

export {Tasks};
Example #16
0
import { Mongo } from "meteor/mongo";
import { SimpleSchema } from "meteor/aldeed:simple-schema";

export const Inquiries = new Mongo.Collection("Inquiries");

Inquiries.schema = new SimpleSchema({
  "school" : { type: Object },
  "school.name": { type: String },
  "school.population": { type: Number },
  "contact" : { type: Object },
  "contact.firstName": { type: String},
  "contact.lastName": { type: String },
  "contact.phone": { type: String },
  "contact.email": {
    type: String,
    regEx: SimpleSchema.RegEx.Email
  },
  eventSlotId: {
    type: String,
    regEx: SimpleSchema.RegEx.Id
  },
  accepted: { type: Boolean }
});

Inquiries.attachSchema(Inquiries.schema);
Example #17
0
m603forms.attachSchema(new SimpleSchema({
/* одна запись в этой колл. = все об этом тесте или об одной его версии/форме, а также
все общие данные для формы теста в целом, для всех заданий     */
// ТИПОВЫЕ данные текущего теста, имеющиеся почти у всех тестов
  numberin: {
    type: Number, 
    label: "Номер формы или версии (0 = методика вообще, во всех ее формах, общая информация)"
  },
  notesDev: {
    type: String,  // обязательно число, иначе не будет стыковаться с числом - реактивной переменной!
    label: "Заметки по разработке",
    optional: true
  },
  code: {
    type: String,
    label: "Код формы или версии (напр., буквенно-числовой, для пользователя/респондента)",
    optional: true
  },

  nameShort: { // в базовой форме = имя методики в целом
    type: String,
    label: "Краткое имя",
    optional: true
  },
  nameLong: {
    type: String,
    label: "Полное имя",
    optional: true
  },

  author: {
    type: String,
    label: "Автор(ы)",
    optional: true
  },

  descrShort: {
    type: String,
    label: "Краткое описание",
    autoform: {
      rows: 2  // текстовое поле на ... строк
      },
    optional: true
  },
  descrLong: {
    type: String,
    label: "Развернутое описание",
    autoform: {
      rows: 7  // текстовое поле на ... строк
      },
    optional: true
  },

  formScales: {
    type: [String],
    label: "Шкалы, используемые в данной форме", 
/* null=пусто (по умолчанию) - все шкалы */
    optional: true
  },
  
  formTypeSequence: {
    type: String,
    label: "Тип формы/теста по последовательности вывода заданий", 
/* null=пусто (по умолчанию) - вывод по порядку внутр. номеров (возможно изменение порядка без смены id,
                завершение по кол-ву всех заданий, получаемому из коллекции заданий 
   sequenceString - по завершению последовательности, указанной в sequenceData,
                ... - по ..., указанной в sequenceData
   random   - случайный
   adoptive - адаптивный режим ... */
    optional: true
  },
  sequenceString: {
    type: String,
    label: "Последовательность или др. данные для вывода", // в соотв-и с указанным выше режимом вывода заданий
    optional: true
  },
  
  pictWww: { // если нет, создается по умолчанию по номеру метода
    type: String,
    label: "Путь к картинкам, по умолчанию http://testpsy.net/m/603/p",
    optional: true
  },

//****************** Отладочные данные
  resEml: { // куда отправлять протокол тестирования сразу после гео завершения - разработчику, админу методик, например
    type: String,
    label: "Email для автоотправки протокола (для 2-х адресов - автопересылку на почте 1-го адреса)",
    optional: true
  },

//****************** Типовые страницы инструкций
  instrGen1: {
    type: String,
    label: "Инструкция 1 (можно использовать теги HTML)",
    autoform: {
      rows: 3  // текстовое поле на ... строк
      },
    optional: true
  }, // в хелпере ТРОЙНЫЕ СКОБКИ используются для того, чтобы строку от хелпера обрабатывать как HTML если ДВОЙНЫЕ - то выведется строка вместе с кодами HTML в явном виде !!!

  instrGen2: { // вывод в окно пока не сделан (не нужно для 603)
    type: String,
    label: "Инструкция 2 - доп. страница (можно использовать теги HTML)",
    autoform: {
      rows: 3  // текстовое поле на ... строк
      },
    optional: true
  }, // в хелпере ТРОЙНЫЕ СКОБКИ используются для того, чтобы строку от хелпера обрабатывать как HTML если ДВОЙНЫЕ - то выведется строка вместе с кодами HTML в явном виде !!!

  instrGen9: { // вывод в окно пока не сделан (не нужно для 603)
    type: String,
    label: "Инструкция 9 - переход к тесту (можно использовать теги HTML)",
    autoform: {
      rows: 3  // текстовое поле на ... строк
      },
    optional: true
  }, // в хелпере ТРОЙНЫЕ СКОБКИ используются для того, чтобы строку от хелпера обрабатывать как HTML если ДВОЙНЫЕ - то выведется строка вместе с кодами HTML в явном виде !!!


//****************** Уникальные данные ТОЛЬКО ЭТОЙ МЕТОДИКИ

  timerAtSt1: {
    type: Number,
    label: "Длительность (мс) экспозиции первой картинки задания (на этапе 1)",
    optional: true
  },
  timerAtSt210: {
    type: Number,
    label: "Длительность (мс) экспозиции крестика фиксации взгляда на этапе 2",
    optional: true
  },
  timerAtSt211: {
    type: Number,
    label: "Длительность (мс) экспозиции картинки на этапе 2",
    optional: true
  },

  stage1txt: {
    type: String,
    label: "Текст вопроса этапа 1",
    optional: true
  },
  stage1nonsense: {
    type: String,
    label: "Текст сообщения о смысловой ошибке этапа 1",
    optional: true
  },
  stage1to2txt: {
    type: String,
    label: "Текст промежуточный от этапа 1 к 2 (можно использовать теги HTML)",
    autoform: {
      rows: 3  // текстовое поле на ... строк
      },
    optional: true
  },  // в хелпере ТРОЙНЫЕ СКОБКИ используются для того, чтобы строку от хелпера обрабатывать как HTML если ДВОЙНЫЕ - то выведется строка вместе с кодами HTML в явном виде !!!

// СПИСОК СЛОВ для КНОПОК для этапа 1 каждого задания
  st1List: {  // массив объектов - предлагаемых ответов на задания (и их свойств)
  type: [Object],  
  label: "Список текстов для кнопок на 1-м этапе заданий",
  optional: true
    },
    "st1List.$.number": {
      type: Number,
      label: "Номер-ID слова/текста/кнопки",
      optional: true
    },
    "st1List.$.text": { 
      type: String,
      label: "Текст для кнопки",
      optional: true
    },  

  

    
}));
Example #18
0
Meteor.startup(function () {
    DepExpList.schema.i18n("acc.depExpList.schema");
    DepExpList.attachSchema(DepExpList.schema);
});
Example #19
0
        allowedValues: ['Inactive', 'Active', 'Reschedule', 'Close']
    },
    activeDate: {
        type: Date,
        label: 'Active date',
        optional: true,
        autoform: {
            afFieldInput: {
                type: 'bootstrap-datetimepicker',
                dateTimePickerOptions: {
                    format: 'DD/MM/YYYY',
                    showTodayButton: true
                }
            }
        }
    },
    rescheduleDate: {
        type: Date,
        optional: true
    },
    closeDate: {
        type: Date,
        optional: true
    },
    branchId: {
        type: String
    }
});

Borrowing.attachSchema([Borrowing.generalSchema]);
Example #20
0
  driverId: {
    type: String,
    label: "Driver ID",
    regEx: SimpleSchema.RegEx.Id
  },
  price: {
    type: Number,
    label: "Price",
    defaultValue: 0
  },
  createdAt: {
    type: Date,
    label: "Created at"
  }
});

Offers.attachSchema(OffersSchema);

if (Meteor.isServer) {
  Meteor.publish('offers', function offersPublication() {
    return Offers.find({
        driverId: this.userId
    });
  });

  Meteor.publish('offersByRequest', function offersPublication(requestId) {
    return Offers.find({
        requestId: requestId
    });
  });
}
Example #21
0
import { Mongo } from "meteor/mongo";
import * as Schemas from "./schemas";

/**
* Discounts Collection
* @type {Object}
* @desc Collection for custom discount rates
* for dollar, percentage, and shipping
* discount rates.
*/
export const Discounts = new Mongo.Collection("Discounts");

Discounts.attachSchema(Schemas.Discounts);
        type: Schemas.Address,
        optional: true,
    },
    createdAt: {
        type: Date,
        autoValue: function() {
            if (this.isInsert && (!this.isSet || this.value.length === 0)) {
                return new Date()
            }
        }
    },
    lastUpdated: {
        type: Date,
        autoValue: function() {
            return new Date()
        }
    },
    createdBy: {
        type: String,
        autoValue: function() {
            if (this.isInsert && (!this.isSet || this.value.length === 0)) {
                return Meteor.userId();
            }
        }
    }      
});

ProcurementOrgs.attachSchema(ProcurementOrgs.schema);


Meteor.startup(function () {
    CloseChartAccountPerMonth.schema.i18n("acc.closeChartAccountPerMonth.schema");
    CloseChartAccountPerMonth.attachSchema(CloseChartAccountPerMonth.schema);
});
Example #24
0
        allowedValues: STATUS_TYPES,
        defaultValue: STATUS_NORMAL
        //autoform: {
        //    options: STATUS_AUTO_FORM
        //}
    },

    /////////////////////
    // Sketch Source
    /////////////////////

    supportedBoards: {
        type: [String], label: "Supported boards / cores",
        optional: true
    },

    usedModules: {
        type: [String], label: "Modules Used",
        optional: true
    },

    sourceCodeUrl: {
        type: String, label: "Sketch source code url",
        optional: true
    },
});

C_Projects.attachSchema(schema);

export default C_Projects;
/**
 * Created by josh.welham on 17/07/16.
 */

import {Mongo} from 'meteor/mongo';
import Schema from './../schema/posts';

const Posts = new Mongo.Collection('posts');

SimpleSchema.extendOptions({
  materialForm: Match.Optional(Object)
});

const PostsSchema = new SimpleSchema(Schema);

Posts.attachSchema(PostsSchema);

export {Posts, PostsSchema};
Example #26
0
import { Mongo } from "meteor/mongo";
import { TaxCodes as TaxCodesSchema } from "./schemas";

/**
 * @name TaxCodes
 * @memberof Collections
 * @type {MongoCollection}
 */
export const TaxCodes = new Mongo.Collection("TaxCodes");

TaxCodes.attachSchema(TaxCodesSchema);
Example #27
0
    type: String,
    label: 'The source of the picture.',
  },
  ownerId:{
    type: String,
    label: 'The owner of the picture.',
  },
  date:{
    type: Date,
    label: 'The date of the picture.',
  },
  subjects:{
    type: [Object],
    label: 'The subjects in the picture.'
  }
});

Pictures.attachSchema(Pictures.schema);


Factory.define('picture', Pictures, {
  title: () => faker.hacker.phrase(),
  src: () => faker.image.imageUrl(),
  ownerId: () => faker.random.uuid(),
  date: () => faker.date.past(),
  subjects: () => [
    { name : faker.name.findName(), id : faker.random.uuid() },
    { name : faker.name.findName(), id : faker.random.uuid() },
  ],
});
Example #28
0
  featured: {type:Boolean, defaultValue:false},
  favorites:{type:Number, defaultValue:0, min:0},
  files: {type:Array, optional:true},
  "files.$":{type:Object},
  "files.$type":{type:String},
  "files.$url":{type:String},
  created_at: {
    type:Date,
    autoValue: function(){
      if(this.isInsert){
        return new Date();
      }else if(this.isUpsert){
        return {$setOnInsert: new Date()};
      }else{
        this.unset();
      }
    }
  },
  updated_at: {type:Date,
    autoValue: function(){
      if(this.isUpdate){
        return new Date();
      }
    },
    denyInsert: true,
    optional: true
  }
});

Resources.attachSchema(Schema.Resources);
Example #29
0
import moment from 'moment-timezone';
import { _ } from 'meteor/underscore';

import { ActionSchema } from '../schemas/action-schema';
import { NonConformities } from './non-conformities';
import { Risks } from './risks';
import { WorkItems } from './work-items';
import {
  ActionUndoTimeInHours,
  ProblemTypes,
  CollectionNames,
} from '../constants';
import { getActionWorkflowType } from '../helpers';

const Actions = new Mongo.Collection(CollectionNames.ACTIONS);
Actions.attachSchema(ActionSchema);

const getLinkedDocsIds = (linkedDocs = [], docType) => _.pluck(
  _.filter(
    linkedDocs,
    ({ documentType }) => documentType === docType,
  ),
  'documentId',
);

Actions.helpers({
  getLinkedNCsIds() {
    const NCIds = getLinkedDocsIds(this.linkedTo, ProblemTypes.NON_CONFORMITY);
    const PGIds = getLinkedDocsIds(this.linkedTo, ProblemTypes.POTENTIAL_GAIN);
    return NCIds.concat(PGIds);
  },
Example #30
0
        label: "Group members"
    },

    "menu": {
        type: [MenuItemSchema],
        label: "Group menu id"
    },

    "orders": {
        type: [OrderSchema],
        label: "Group list of orders",
        optional: true
    },

    "owner": {
        type: String,
        label: "Group owner",
        optional: false
    },

    "createdAt": {
        type: Date,
        label: "Date of group creation",
        optional: false
    }
})

Groups = new Mongo.Collection('groups')
Groups.attachSchema(GroupSchema)

export default Groups