GithubHelp home page GithubHelp logo

meteor-collection2-core's Introduction

meteor-collection2-core's People

Contributors

aldeed avatar jasonphillips avatar newsiberian avatar spencern avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

meteor-collection2-core's Issues

Replace underscore

Similar to this Simple Schema PR, it would be good to switch from underscore to lodash so they can be used together with a lighter client load.

There are 14 uses of underscore, which I have grepped and listed here for reference during replacement.

64:        if(_.isEqual(schema.selector, selector)) {
114:_.each([Mongo.Collection, LocalCollection], function (obj) {
168:_.each(['insert', 'update'], function(methodName) {
172:        args = _.toArray(arguments);
243:  var validatedObjectWasInitiallyEmpty = _.isEmpty(doc);
331:      extendAutoValueContext: _.extend({
372:  if (Meteor.isServer && isUpsert && _.isObject(selector)) {
374:    docToValidate.$set = _.clone(selector);
376:    _.extend(docToValidate.$set, set);
388:  if (!validatedObjectWasInitiallyEmpty && _.isEmpty(docToValidate)) {
402:      extendedCustomContext: _.extend({
478:    var args = _.toArray(arguments);
492:    var args = _.toArray(arguments);
608:    c.deny(_.extend({

I'd like to do this myself sometime soon, but I can't guarantee I'll get to it, which is why I'm submitting it as an issue.

Adding an updatedAt field to the user collection results in a 403 Access denied message

I am having a problem while trying to save the profile schema within my UserCollection.

I extend all of my collections with a default schema object that I pass to my collection via:
collection.attachSchema(schema);

After adding the autovalue to my updatedAt field, I can't save forms that use parts of the usercollection schema:

    updatedAt: {
      type: Date,
      optional: true,
      autoValue: function() {
        if (this.isUpdate) {
          return new Date();
        } else {
          this.unset();
        }
      },
      denyInsert: true,
    },
    updateBy: {
      type: String,
      optional: true,
      autoValue: function() {
        if (this.isUpdate && this.userId) {
          return this.userId;
        } else {
          this.unset();
        }
      },
      denyInsert: true,
    },

Notes:

  • The above problem only happens on parts of my user schema (profile and settings objects), all other forms save succesfully.
  • The updatedAt and updateBy are actually updated after a "save", the rest of the data is left un-updated or unchanged so to say

I get the following error after debugging autoform via console.log():

Error in user-account update Object
{ stack: "errorClass@http://localhost:3000/pa…", error: 403, reason: "Access denied", details: undefined, message: "Access denied [403]", errorType: "Meteor.Error" }

Sidenote: The above error hasn't given me new clue on the problem. Yes, access denied, I dropped all permits and validations and still, I get access denied.

Can anyone help me with what I am doing wrong, or am I hitting a bug or just using collection2 in doing something that it shouldn't?

Thanks in advance.

Error: _schema key is missing "type"

Hello,
Am trying to define a schema for a collection. Am getting the following errors:

Exception in callback of async function: Error: _schema key is missing "type"
in file simpl-schema/dist/SimpleSchema.js:858:26

Allow passing options further

cult-of-coders/redis-oplog#207

Basically, when we do client-side mutations, we need this package to not strip out the options, but pass them along.

So what we basically need, is a way to configure this package, to allow passing options to the .insert(). Update already takes options so we're fine with that, and remove doesn't get overridden.

Invalid updates fail silently

Related to #18, whenever an invalid property is detected, it seems like it's scrubbed out of the update without any error (even when logging out the error callback). It'd be great to get more visibility into what's actually going on when something goes wrong.

default validationContext automatically added to collection

I have a strange issue in a private codebase where a collection has an automatically added validationContext, called default. This creates weird validation errors during my tests, as it complains in this case:

myMethod: ({ value, id }) => {
  const objectToUpdate = MyCollection.findOne(id)
  console.log(objectToUpdate.nested.someOtherValue) // it is defined

 MyCollection.update(id, { $push: { 'nested.someArray': value } }); // Throws an error
}

It complains that nested.someOtherValue is required (another value that is in the schema), even though this nested.someOtherValue is clearly present on the object before the $push update to someArray.

What I get: Error: Some Other Value is required I20171214-15:18:58.291(1)? at getErrorObject (packages/aldeed:collection2-core/collection2.js:464:15)

And a bit below:

invalidKeys: [ {
  name: 'nested.someOtherValue',
  type: 'required',
  value: undefined
 } ],

I am unable to replicate this in a bare repo. It seems like this package's validation sees this as an update of the entire nested object and throws?

Collection2 `$set` with an array of objects

This might not be an issue, I not sure. Basically, I'm using simple-schema and colelction2 with reactjs. I have an array of Objects that I'm trying to save into a collection. I'm currently using $push to update my collection which works, however, I would like to use $set to get access to the cleaning functionality of collection2. When I use $set I get an array with no objects in my collection. I'm a little confused as to what is causing this.

The collection when using $set looks like:

 {
  "_id": "ephCX8y8pt5AcqNNY",
  "userId": "yLyBjWzfbSpP5nG8h",
  "languages": []
}
const ProfileCandidateSchema = new SimpleSchema({
  userId: {
    type: String,
    regEx: SimpleSchema.RegEx.Id
  },
  languages: { type: Array, optional: true },
  'languages.$': { type: Object, optional: true },
  'languages.$.uniqueId': { type: Number, optional: true },
  'languages.$.language': { type: String, optional: true },
  'languages.$.proficiency': { type: String, optional: true }
}, {
  clean: {
    filter: true,
    autoConvert: true,
    removeEmptyStrings: true,
    trimStrings: true,
    getAutoValues: true,
    removeNullsFromArrays: true
  }
});
const updateEducationHisotry = this.state.languages.map((language) => {
  ProfileCandidate.update({
    _id: this.state.profileCandidateCollectionId
  }, {
    $set: {
      languages: [{
        language: language.language,
        uniqueId: language.uniqueId,
        proficiency: language.proficiency
      }]
    }
  }, (error, result) => {
    if (error) {
      console.log("ereer: ", error.invalidKeys);
      Bert.alert('Oops. It looks like something went wrong with the database save. Please try again or contact us.', 'danger', 'growl-top-right');
    }
    if (result) {
      Bert.alert('Languages saved.', 'success', 'growl-top-right');
    }
  })
});

How to get currently attached schema?

How can I get a schema definition that is currently attached to some collection?

export const mySchema = new SimpleSchema({ ... });
MyColletion.attachSchema(mySchema);

Now, on the client side, I would like to get some label:

//something like
MyCollection.getSchema().label("fieldName");

How can I do this?

I know I could import mySchema and use that, but it's not what I'm looking for since it requires prior knowledge of schema definition that was attached.

$push to Array doesn't add default values

I have a schema with an array of objects, and that object is defined with a few non-optional defaultValues. I'd like to be able to $push an empty object to that array and have it automatically populated with all the necessary defaultValues, but instead it throws an error

Exception while invoking method 'methodName' Error: My field is required

Not sure if this is consistent with the insert behaviour?

Not compatible with Meteor 1.4.2.7??

I got this error message when trying to upgrade the package to its latest version (2.0).
Please help.. I want to make sure I can still use the package.

$ meteor update
This project is already at Meteor 1.4.2.7, the latest release.
Your top-level dependencies are at their latest compatible versions.

Newer versions of the following indirect dependencies are available:

  • aldeed:collection2-core 1.2.0 (2.0.0 is available)
  • aldeed:schema-deny 1.1.0 (2.0.0 is available)
  • aldeed:schema-index 1.1.1 (2.0.0 is available)
    To update one or more of these packages, pass their names to
    meteor update, or just run meteor update --all-packages.

$ meteor update aldeed:collection2-core
The specified packages are at their latest compatible versions.

autoValue inconsistency between server and client

Upgrading from 2.0.1 to 2.0.4 introduces inconsistencies.

Comments.schema = new SimpleSchema({
  createdAt: {
    type: Date,
    autoValue() {
      if (this.isInsert) {
        return new Date();
      }
    }
  },
  title: {
    type: String
  }
});

Running insert query like this:

Comments.insert({ title: 'Lorem ipsum' });

results in this document on client

{
  title: 'Lorem ipsum'
}

and this document on server

{
  createdAt: '2017-11-21T17:05:48.372+0000',
  title: 'Lorem ipsum'
}

So it seems that autoValue is not working properly on the client. I tested and the function runs fine though.

[FEATURES] Add Typings

It would be nice to include typings for those trying to use Angular Meteor. Working on a PR.

Cannot find module './SimpleSchema' error

Hi there,

I have installed collection2-core on my meteor project as suggested:

$ meteor add aldeed:collection2-core
$ meteor npm install --save simpl-schema

Right at meteor run I get a strage error:

W20170730-09:36:24.740(2)? (STDERR) /Users/USER/.meteor/packages/meteor-tool/.1.5.1.15hiv04++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280
W20170730-09:36:24.742(2)? (STDERR) 						throw(ex);
W20170730-09:36:24.743(2)? (STDERR) 						^
W20170730-09:36:24.745(2)? (STDERR)
W20170730-09:36:24.747(2)? (STDERR) Error: Cannot find module './SimpleSchema'
W20170730-09:36:24.748(2)? (STDERR)     at makeMissingError (packages/modules-runtime.js:221:12)
W20170730-09:36:24.749(2)? (STDERR)     at require (packages/modules-runtime.js:231:19)
W20170730-09:36:24.754(2)? (STDERR)     at meteorInstall.node_modules.simpl-schema.dist.main.js (packages/modules.js:521:21)
W20170730-09:36:24.755(2)? (STDERR)     at fileEvaluate (packages/modules-runtime.js:333:9)
W20170730-09:36:24.756(2)? (STDERR)     at require (packages/modules-runtime.js:228:16)
W20170730-09:36:24.756(2)? (STDERR)     at meteorInstall.node_modules.meteor.aldeed:collection2-core.collection2.js (packages/aldeed:collection2-core/collection2.js:9:22)
W20170730-09:36:24.757(2)? (STDERR)     at fileEvaluate (packages/modules-runtime.js:333:9)
W20170730-09:36:24.758(2)? (STDERR)     at require (packages/modules-runtime.js:228:16)
W20170730-09:36:24.760(2)? (STDERR)     at /PATH_TO_MY_PROJECT/.meteor/local/build/programs/server/packages/aldeed_collection2-core.js:725:15
W20170730-09:36:24.761(2)? (STDERR)     at /PATH_TO_MY_PROJECT/.meteor/local/build/programs/server/packages/aldeed_collection2-core.js:736:3

At /PATH_TO_MY_PROJECT/.meteor/local/build/programs/server/packages/aldeed_collection2-core.js:725, I find:

var exports = require("./node_modules/meteor/aldeed:collection2-core/collection2.js");

But I realized that I don't have a ./node_modules/meteor directory at all. Before trying to install these packages, the app was starting up just fine.

$and is not allowed in an update QUERY SELECTOR by the schema

Hi There,

Encountered what i think is an odd bug, I'm trying to update a doc with a complex selector, and keep getting this error: $and is not allowed by the schema,

By bypassing collection2, everything works as expected, below is my function:

export const push = (data, callback) => driverData.collection.update({
  $and: [
    { driverId: data.driverId },
    { createdAtWeekDay: new Date().getUTCDay() },
    { createdAt: { $gt: new Date(Date.now() - (60 * 60 * 24 * 1000)) } },
  ],
}, {
  $setOnInsert: { driverId: data.driverId },
  $push: {
    data: _.extend({}, _.omit(data, 'driverId'), { timestamp: new Date() }),
  },
}, {
  bypassCollection2: false,
  upsert: true,
  multi: false,
}, (error, result) => { // update callback
  if (callback && typeof callback === 'function') {
    return callback(error, result);
  }
});

clearly, it seems to be trying to validate my update query, which seems odd to me, but maybe I've missed something in the docs?

How do I send you money to support this?

First: thanks for doing this! Second: I'd love to send you a few bucks because I'm using collection2 on my project and I like it. How do I do this?

I've found @aldeed on gittip (or gratipay or whatever it's called now) but I find it incredibly confusing and hard to figure out how to actually support someone through that. Did you consider Patreon or donorbox or something like that?

Problem with multi attacheSchema()?

I try to create soft remove library
Collection

import {Mongo} from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';

const AccountTypes = new Mongo.Collection('acc_accountTypes');

AccountTypes.schema = new SimpleSchema({
    code: {
        type: String,
        unique: true
    },
    name: {
        type: String,
        unique: true
    },
    nature: {
        type: String,
        allowedValues: ['Asset', 'Liability', 'Equity', 'Revenue', 'Expense']
    },
    status: {
        type: String,
    },
    memo: {
        type: String,
        optional: true
    }
});

AccountTypes.attachSchema(AccountTypes.schema);
export default AccountTypes;

Library

// Soft Remove
CollectionExtensions.addPrototype('softRemove', function (selector = {}) {
    let self = this;
    const schema = new SimpleSchema({
        removed: Boolean,
        removedAt: Date,
        removedBy: String
    });
    self.attachSchema(schema, {selector: {type: 'softRemove'}});

    return self.direct.update(
        selector,
        {
            $set: {
                // selector: {type: 'softRemove'}, // where to put this
                removed: true,
                removedAt: new Date(),
                removedBy: Meteor.userId()
            }
        },
        {multi: true},
        (error, num) => {
            if (num) {
                console.log('soft remove');
            }
        }
    );
});

Please help me

How to use ValidateOne for array?

var s = new SimpleSchema({
  'field': {
    type: Array
  },
  'field.$': {
    type: String
  }
});
var c = s.newContext();
c.validateOne({ $push: { 'field': 123 } }, 'field', { modifier: true }); // true

Unique index error not mapped

Hi

I do have a schema defined as so:

export var mySchema= new SimpleSchema({
  code: {    type: String,    min:0,    max: 10,    index: true,    unique: true  },
  name: {    type: String,    min: 1,    index: true,    unique: true  }
});

If intserting duplicated values, the error that I obtain is 11000 E11000 duplicate key error index: meteor.country.$code_1 dup key: { : "C1" } [409]

As per https://github.com/aldeed/meteor-collection2-core/blob/master/lib/collection2.js#L488, C2 is not found (C1) here and the error is not mapped.

Is that normal ? Whats the purpose of checking only C2 ?

Regards

Autovalue bug when inserting into array

The example for keeping updates history for a field appears as though it is longer working with simpl-schema 0.1.0 and Collection2-core 2.0.0.

From https://github.com/aldeed/meteor-collection2-core/:

// Whenever the "content" field is updated, automatically
  // update a history array.
  updatesHistory: {
    type: Array,
    optional: true,
    autoValue: function() {
      var content = this.field("content");
      if (content.isSet) {
        if (this.isInsert) {
          return [{
              date: new Date(),
              content: content.value
            }];
        } else {
          return {
            $push: {
              date: new Date,
              content: content.value
            }
          };
        }
      } else {
        this.unset();
      }
    }
  },
  'updatesHistory.$': {
    type: Object,
  },
  'updatesHistory.$.date': {
    type: Date,
    optional: true
  },
  'updatesHistory.$.content': {
    type: String,
    optional: true
  },

When using this in a collection it appears that autovalue unnecessarily creates an extra array doing the insert, yielding the error in my sample app:

titleUpdatesHistory.0.0 is not allowed by the schema

Example project here:

https://github.com/benlavalley/autoValueBug

Tried to put together as succinct an example as possible. I could dig into simpl-schema/collection2-core code more but I spent a number of hours working on this one already (moving from simpl-schema 0.0.3 to 0.1.0, adding babel-polyfill to my app for it, etc) and I think the right person will be able to swiftly figure this one out :)

Not sure if this belonged in simpl-schema or not - if it did let me know and I can create an issue there.

If I'm fouling something up or missed seeing a change in the new simpl-schema/collection2 versions I apologize - these packages are awesome and I'd hate to know I was polluting the issues section with something that was my fault.

autoValues not working when updating with null-prototype objects

Found this by resolving #23. Might be somehow related to #8. Think this deserves a separate issue. The following is a 99% copy paste of this comment in #23:

Let's say we have a Collection with an attached schema that has a field defined with an autoValue function. Let's further say doc is an object with Object.getPrototypeOf(doc) equals null and it is valid by the schema of the Collection. When I do an update

Collection.update({
  _id: doc._id
}, {
  $set: doc
})

then no matter what the autoValue function may return (and it will be called), the result will not appear in the updated document. But if I do the update this way:

Collection.update({
  _id: doc._id
}, {
  $set: {
    ...doc
  }
})

where Object.getPrototypeOf({ ...doc }) equals {} it works and the autoValue fields will be there as expected.
So, it seems collection2 doesn't like null-prototype objects.

Update is not working for multiple schemas when using update operators

When I use multiple schemas and try to perform a collection.update using $set, $inc or other update operators, collection2 seems to search for a matching schema using the given document.

The problem is that I'm not giving it a full document on this case.
I'm giving it only a simple object with a single operator like $set in the most cases.

It's throwing the following error:

Uncaught TypeError: Cannot read property 'namedContext' of null
    at Mongo.Collection.doValidate (http://localhost:3000/packages/aldeed_collection2-core.js?hash=084bd3a463b8cca3de6c7568fb6563eeced9b54c:328:31)
    at Mongo.Collection.(anonymous function) [as update] (http://localhost:3000/packages/aldeed_collection2-core.js?hash=084bd3a463b8cca3de6c7568fb6563eeced9b54c:236:25)
    at http://localhost:3000/packages/ohif_measurements.js?hash=23484d634a7fac23ba8f02891cfd66a57cbf28f6:339:36
    at Array.forEach (native)
    at http://localhost:3000/packages/ohif_measurements.js?hash=23484d634a7fac23ba8f02891cfd66a57cbf28f6:398:43
    at Array.forEach (native)
    at MeasurementApi.sortMeasurements (http://localhost:3000/packages/ohif_measurements.js?hash=23484d634a7fac23ba8f02891cfd66a57cbf28f6:390:27)
    at Function.onAdded (http://localhost:3000/packages/ohif_measurements.js?hash=23484d634a7fac23ba8f02891cfd66a57cbf28f6:5939:36)
    at Object.CornerstoneToolsMeasurementAddedImageViewerViewport (http://localhost:3000/app/app.js?hash=343340c2f5094a745997bb9031875a8884279ae2:807:51)
    at http://localhost:3000/packages/blaze.js?hash=10a350f1c0d55cf44d3c99989b04ef2e7e0d23f6:3759:20

Array of objects bug

Hi Aldeed. I'm pretty sure this is a bug, as I can't seem to find a solution. It would be good to get some clarification.

Please tell me what I'm missing here. When I update the Array of objects my collection updates with an empty array. I'm using meteor-collection2-core and node-simple-schema. Since it inserts an empty array, there's no error.

Path: Method

testArray = [{
	"institution": "Swinburn",
	"uniqueId": 1501036480813,
	"qualification": "Bachelor of Commerce",
	"completed": "2017"
}]

ProfileCandidate.update('Ntzj6kE8qZsvSPMEP', {$set: {educationQualifications: testArray}});

Path: Collection

export const ProfileCandidate = new Mongo.Collection('profileCandidate');

const ProfileCandidateSchema = new SimpleSchema({
  userId: {
    type: String,
    regEx: SimpleSchema.RegEx.Id
  },
  educationQualifications: { type: Array, optional: true },
  'educationQualifications.$': { type: Object, optional: true },
  'educationQualifications.$.uniqueId': { type: Number, optional: true },
  'educationQualifications.$.institution': { type: String, optional: true },
  'educationQualifications.$.qualification': { type: String, optional: true },
  'educationQualifications.$.completed': { type: String, optional: true }
});

ProfileCandidate.attachSchema(ProfileCandidateSchema);

Reusing schema results in inconsistent autoValue behavoir

I defined a schema to automatically create createdAt and updatedAt fields:

import SimpleSchema from 'simpl-schema'

const timestampSchema = new SimpleSchema({
  'createdAt': {
    type: Date,
    autoValue () {
      if (this.isInsert) {
        return new Date()
      } else if (this.isUpsert) {
        return { $setOnInsert: new Date() }
      } else {
        this.unset()  // Prevent user from supplying their own value
      }
    }
  },
  'updatedAt': {
    type: Date,
    optional: true,
    autoValue () {
      console.log('updatedAt auto value...')
      if (this.isUpdate) {
        console.log('isUpdate...')
        return new Date()
      }
    }
  }
})

export default timestampSchema

I also have several collections where I attach schemas in the exact same way, like:

import { Mongo } from 'meteor/mongo'
import SimpleSchema from 'simpl-schema'
import timestampSchema from './schemas/timestampSchema'

export const Collection = new Mongo.Collection('collection-name')

const schema = new SimpleSchema({
  '_id': {
    type: String,
    optional: true
  },
 ...
})

Collection.attachSchema(schema)
Collection.attachSchema(timestampSchema)

The collection schemas themselves don't add any autoValues. There's really no difference between the collections other then their names and their field names. There are no other fields named createdAt or updatedAt. Now, when running updates on documents of any of the collections, the following log output appears

updatedAt auto value...
isUpdate...

as expected. But, for some reason, only documents of certain collections will get an updatedAt field. It's always the same collections where it will work and where it won't. I know this sounds very strange and if I saw such an issue I would immediately think there must be some difference that I missed. But how can it be, that the above log output appears for every update but there is no updatedAt field present in the updated document for specific collections? And yes, I checked, the updates themselves did work correctly.

Any help or ideas would be greatly appreciated. Thank you.

TypeError: Cannot read property 'mergedSchema' of undefined

Hello, I tried to add a quickform to edit users profiles, but I get keep getting this error:

Exception in template helper: TypeError: Cannot read property 'mergedSchema' of undefined
    at Object.quickFormContext (http://localhost:3000/packages/aldeed_autoform.js?hash=a18c62226899c358fbb26d882c56bd78f140b218:6424:38)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3051:16
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1715:16
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3103:66
    at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3744:12)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3102:27
    at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?hash=ebf9381e7fc625d41acb0df14995b7614360858a:172:18)
    at http://localhost:3000/packages/aldeed_autoform.js?hash=a18c62226899c358fbb26d882c56bd78f140b218:6387:23
    at wrappedArgFunc (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2960:14)
    at Blaze.View.<anonymous> (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2673:26)
meteor.js?hash=27829e9…:930 Exception in defer callback: TypeError: Cannot read property 'id' of null
    at Blaze.View.<anonymous> (http://localhost:3000/packages/aldeed_autoform.js?hash=a18c62226899c358fbb26d882c56bd78f140b218:6268:24)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1934:20
    at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3744:12)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1932:29
    at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2271:12)
    at viewAutorun (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1931:18)
    at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?hash=9f8a0cec09c662aad5a5e224447b2d4e88d011ef:339:36)
    at new Tracker.Computation (http://localhost:3000/packages/tracker.js?hash=9f8a0cec09c662aad5a5e224447b2d4e88d011ef:229:10)
    at Object.Tracker.autorun (http://localhost:3000/packages/tracker.js?hash=9f8a0cec09c662aad5a5e224447b2d4e88d011ef:604:11)
    at Blaze.View.autorun (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1944:22)
meteor.js?hash=27829e9…:930 Exception in template helper: TypeError: Cannot read property 'mergedSchema' of undefined
    at Object.quickFormContext (http://localhost:3000/packages/aldeed_autoform.js?hash=a18c62226899c358fbb26d882c56bd78f140b218:6424:38)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3051:16
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1715:16
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3103:66
    at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3744:12)
    at http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3102:27
    at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?hash=ebf9381e7fc625d41acb0df14995b7614360858a:172:18)
    at http://localhost:3000/packages/aldeed_autoform.js?hash=a18c62226899c358fbb26d882c56bd78f140b218:6387:23
    at wrappedArgFunc (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2960:14)
    at Blaze.View.<anonymous> (http://localhost:3000/packages/blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2673:26)

Schema definition


import SimpleSchema from 'simpl-schema';
// Required AutoForm setup
SimpleSchema.extendOptions(['autoform']);

const Schema = {};

Schema.Role = new SimpleSchema({
  organization: {
    optional: true,
    type: String, //(Organization)
  },
  specialty: {
    optional: true,
    type: String,
  },
  location: {
    optional: true,
    type: String,
  }, // (Location) ],
});

Schema.UserCountry = new SimpleSchema({
  name: {
    type: String,
  },
  code: {
    type: String,
    regEx: /^[A-Z]{2}$/,
  },
});

Schema.UserProfile = new SimpleSchema({
  firstName: {
    type: String,
    optional: true,
  },
  lastName: {
    type: String,
    optional: true,
  },
  birthDate: {
    type: Date,
    optional: true,
  },
  gender: {
    type: String,
    allowedValues: ['Male', 'Female'],
    optional: true,
  },
  country: {
    type: Schema.UserCountry,
    optional: true,
  },
  telecom: {
    type: Number,
    optional: true,
  },
  role: {
    type: Schema.Role,
    optional: true,
  },
});

Schema.User = new SimpleSchema({
  username: {
    type: String,
    // For accounts-password, either emails or username is required, but not both. It is OK to make this
    // optional here because the accounts-password package does its own validation.
    // Third-party login packages may not require either. Adjust this schema as necessary for your usage.
    optional: true,
  },
  emails: {
    type: Array,
    // For accounts-password, either emails or username is required, but not both. It is OK to make this
    // optional here because the accounts-password package does its own validation.
    // Third-party login packages may not require either. Adjust this schema as necessary for your usage.
    optional: true,
  },
  'emails.$': {
    type: Object,
  },
  'emails.$.address': {
    type: String,
    regEx: SimpleSchema.RegEx.Email,
  },
  'emails.$.verified': {
    type: Boolean,
  },

  createdAt: {
    type: Date,
  },
  profile: {
    type: Schema.UserProfile,
    optional: true,
  },
  // Make sure this services field is in your schema if you're using any of the accounts packages
  services: {
    type: Object,
    optional: true,
    blackbox: true,
  },
  // Add `roles` to your schema if you use the meteor-roles package.
  // Option 1: Object type
  // If you specify that type as Object, you must also specify the
  // `Roles.GLOBAL_GROUP` group whenever you add a user to a role.
  // Example:
  // Roles.addUsersToRoles(userId, ["admin"], Roles.GLOBAL_GROUP);
  // You can't mix and match adding with and without a group since
  // you will fail validation in some cases.
  roles: {
    type: Object,
    optional: true,
    blackbox: true,
  },

  // In order to avoid an 'Exception in setInterval callback' from Meteor
  heartbeat: {
    type: Date,
    optional: true,
  },
  // Status module information  https://github.com/mizzao/meteor-user-status#basic-usage---online-state
  // Public and sent to any client

  status: {
    type: Object,
    optional: true,
    blackbox: true,
  },
});

Meteor.users.attachSchema(Schema.User);

Template

<template name="account">
    {{> quickForm collection="Meteor.users" id="update-user-profile" type="update" doc=currentUser }}

</template>

func is not a function error on insert or update

Following the docs to a tee (pretty sure), any time I insert into or update a collection I get the following error:

Exception while simulating the effect of invoking 'categories.insert' TypeError: func is not a function

Which points to this line in meteor.js:

// Custom whole-doc validators                                                                                       // 356
var docValidators = schema._docValidators.concat(_SimpleSchema.SimpleSchema._docValidators);                         // 357
docValidators.forEach(function (func) {                                                                              // 358
  var errors = func(obj);                                                                                            // 359
  if (!Array.isArray(errors)) throw new Error('Custom doc validator must return an array of error objects');         // 360
  if (errors.length) validationErrors = validationErrors.concat(errors);                                             // 361
}); 

The only way I can get a collection to insert or update is to pass {validate: false}, which defeats the purpose of using a schema. I have code posted on this Stack Overflow issue.

Attach schema to Meteor.users: cannot create users

I get this error message:

Exception while invoking method 'ATCreateUserServer' Error: Created at must be a Date

Schema:

const UserSchema = new SimpleSchema({
  createdAt: {
    type: Date
  },
  //...
});
Meteor.users.attachSchema(UserSchema);

Full exception report:

Exception while invoking method 'ATCreateUserServer' Error: Created at must be a Date
I20161207-22:59:39.868(3)?     at getErrorObject (packages/aldeed_collection2-core.js:480:15)
I20161207-22:59:39.868(3)?     at [object Object].doValidate (packages/aldeed_collection2-core.js:462:13)
I20161207-22:59:39.868(3)?     at [object Object].Mongo.Collection.(anonymous function) [as insert] (packages/aldeed_collection2-core.js:214:25)
I20161207-22:59:39.869(3)?     at AccountsServer.Ap.insertUserDoc (packages/accounts-base/accounts_server.js:1326:25)
I20161207-22:59:39.869(3)?     at _createUser (packages/accounts-password/password_server.js:1009:25)
I20161207-22:59:39.869(3)?     at AccountsServer.Accounts.createUser (packages/accounts-password/password_server.js:1078:10)
I20161207-22:59:39.870(3)?     at [object Object].Meteor.methods.ATCreateUserServer (packages/useraccounts_core.js:1294:27)
I20161207-22:59:39.870(3)?     at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1712:12)
I20161207-22:59:39.871(3)?     at packages/ddp-server/livedata_server.js:711:19
I20161207-22:59:39.871(3)?     at [object Object]._.extend.withValue (packages/meteor.js:1122:17)
I20161207-22:59:39.875(3)? Sanitized and reported to the client as: Created at must be a Date [400]

I can't figure out how to fix it. Please, help!

Set cleaning defaults differently for insert vs update

Is there currently a way to globally set on/off validation options like filter, autoConvert etc.? I like for example filter to be false for all insert but not update calls.

I just see in the code

const defaultCleanOptions = {
  filter: true,
  autoConvert: true,
  removeEmptyStrings: true,
  trimStrings: true,
  removeNullsFromArrays: false,
};

Is there a reason, that this is not implemented? (too complicated, effort vs. outcome, no real use case etc.)

How to test when using this.userID in schema

I am trying to write tests for a method that has inserts to a schema that rely on this.userId but as you might have guessed, that context doesn't exist on a server to server action.

Is there a way to get the userId context that I can switch over to when something like isfromTrustedCode is true?

Otherwise is the only/best solution to extend the context all over my applications database interactions so that I can guarantee the userId context is passed in??

Error saying that a value is required even though the value is provided

This is my Schema:

Schema.UserProfile = new SimpleSchema({
    name: {
        type: String,
        label: "Name",
        optional: false
    },
...
Schema.User = new SimpleSchema({
    userProfile: {
        type: Schema.UserProfile,
        optional: false
    },

and insert method:

var profile = {
        name: 'Sacha Greif',
        email: "[email protected]",
        phone: 555999000
    };
    var adminId = Accounts.createUser({
        userProfile: profile,
...

but I get error:

Error: Name is required
    at getErrorObject (packages/aldeed:collection2-core/collection2.js:453:15)
    at [object Object].doValidate (packages/aldeed:collection2-core/collection2.js:435:13)
    at [object Object].Mongo.Collection.(anonymous function) [as insert] (packages/aldeed:collection2-core/collection2.js:187:25)
    at AccountsServer.Ap.insertUserDoc (packages/accounts-base/accounts_server.js:1325:25)
    at createUser (packages/accounts-password/password_server.js:1050:25)
    at AccountsServer.Accounts.createUser (packages/accounts-password/password_server.js:1119:10)
    at meteorInstall.server.setup.fixtures.adminFixture.js (server/setup/fixtures/adminFixture.js:22:28)
    at fileEvaluate (packages\modules-runtime.js:333:9)
    at require (packages\modules-runtime.js:228:16)

Is it bug or I'm doing something wrong? It was working with old (not core) aldeed:simple-schema and collection2

I get the same bug on first level (not nested) fields.

Meteor.users.simpleSchema().validate(u); does not throw any errors

Found both autoValue and defaultValue. Ignoring defaultValue

I've got a boolean in a SimpleSchema that should be false by default:

{ isCompleted: {type: Boolean, defaultValue: false} }

But I get this error:

SimpleSchema: Found both autoValue and defaultValue options for "isCompleted". Ignoring defaultValue

I don't have autoValue set for that key so I'm not sure where that's coming from.

$ meteor list
aldeed:collection2-core      2.0.1  Core package for aldeed:collection2
aldeed:schema-deny           2.0.0  Deny inserting or updating certain properties through schema options
$ npm list
[...]
└─┬ [email protected]
[...]

Error: Field name duplication not allowed with modifiers

After migrating from the Meteor package to this one, I've started getting Field name duplication not allowed with modifiers errors. I'm not really sure where they're coming from, because I don't see any duplicate field names in my modifiers… Any thoughts?

(opening this instead of longshotlabs/simpl-schema#89 because the error goes away if I disable Collection2)

Multiple schemas feature not working

Multiple schemas feature not working. I have code as below:

import { Meteor } from "meteor/meteor";
import SimpleSchema from 'simpl-schema';

Profiles = new Mongo.Collection('Profiles');

SchemaProfile = new SimpleSchema({
    userId: {
        type: String,
    },
    firstName: {
        type: String,
        optional: true,
    },
    lastName: {
        type: String,
        optional: true,
    },
    role: {
        type: Number,
        allowedValues: [UserGroup.EMPLOYEE, UserGroup.EMPLOYER, UserGroup.ADMINISTRATOR]
    },
});

SchemaEmployeeProfile = SchemaProfile.extend({
    daysRemaining: {
        type: Number,
        min: 0,
        defaultValue: 20,
    },
    position: {
        type: String,
    }
});

SchemaEmployerProfile = SchemaProfile.extend({
    someOtherField: {
        type: String,
    }
});

Profiles.attachSchema(SchemaEmployeeProfile, {selector: {role: UserGroup.EMPLOYEE}});
Profiles.attachSchema(SchemaEmployerProfile, {selector: {role: UserGroup.EMPLOYER}});

Trying to create new item in Profiles collection:

const profileId = Profiles.insert({
	userId: userId,
	role: UserGroup.EMPLOYER,
}, { selector: { role: UserGroup.EMPLOYER }});

Error:

Exception while invoking method 'employerCreate' Error: position is required
at getErrorObject (packages/aldeed:collection2-core/collection2.js:453:15)
at [object Object].doValidate (packages/aldeed:collection2-core/collection2.js:435:13)
at [object Object].Mongo.Collection.(anonymous function) [as insert] (packages/aldeed:collection2-core/collection2.js:187:25)
at [object Object].Meteor.methods.employerCreate (imports/server/methods/employers.js:21:30)
at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1737:12)
at packages/ddp-server/livedata_server.js:719:19
at [object Object]._.extend.withValue (packages/meteor.js:1122:17)
at packages/ddp-server/livedata_server.js:717:40
at [object Object]._.extend.withValue (packages/meteor.js:1122:17)
at packages/ddp-server/livedata_server.js:715:46
Sanitized and reported to the client as: position is required [400]

So, it validates against SchemaEmployeeProfile, not SchemaEmployerProfile, as it should.

Please, fix it.

How do I combine Schemas using Collection2-core?

I've seen examples where Schemas are combined using meteor-simple-schema how do I do that using this package? For instance when I do something like this:
items: { type: Array, optional: true }, "items.$": { type: Shema.CartItem },
I get an error that item items.$ requires a type. Can't I use a Schema as the type?

Support complicated selectors for upserts

Example:
schema:

{
  createdAt: { type: Date },
  a: { type: Number },
  b: { type: Number },
  c: { type: Date, optional: true }
}

Code:

collection.upsert(
  { a: 1, b: 2, c: { $exists: false } }, 
  { 
    $setOnInsert: { createdAt: new Date() }, 
    $set: { a: 1, b: 2 }
  })

Basically, I want a document where a is 1, b is 2 that does not have a c field (which is a flag type field, the Date simply indicating when it was set). Instead, this gives a schema validation error that says { $exists: false } is not a Date.

It seems that the fields of the selector are being copied into the $set for validation (based on comments in the code). This obviously won't work for any field that has a mongodb keyword in its value, like the above.

Error: Cannot find module ‘meteor/tmeasday:check-npm-versions’

Issue happens to my existing project after upgrading from 1.5.x to 1.,6

Completely uninstalled Meteor from Windows 10 and installed again.

Same for new project. To reproduce

Create an empty project with “meteor create”

Install collection2-core
meteor add aldeed:collection2-core
meteor npm install --save simpl-schema

run with “meteor”

D:\DEV-ML\htdocs\MeteorNix>meteor
[[[[[ ~\D\DEV-ML\htdocs\MeteorNix ]]]]]

=> Started proxy.
=> Started MongoDB.
W20171117-21:43:55.448(1)? (STDERR) d:\Users\markus\AppData\Local\.meteor\packages\meteor-tool\1.6.0\mt-os.windows.x86_64\dev_bundle\server-lib\node_modules\fibers\future.js:280
W20171117-21:43:55.486(1)? (STDERR)                                             throw(ex);
W20171117-21:43:55.489(1)? (STDERR)                                             ^
W20171117-21:43:55.490(1)? (STDERR)
W20171117-21:43:55.491(1)? (STDERR) Error: Cannot find module 'meteor/tmeasday:check-npm-versions'
W20171117-21:43:55.492(1)? (STDERR)     at Function.Module._resolveFilename (module.js:513:15)
W20171117-21:43:55.493(1)? (STDERR)     at Function.resolve (internal/module.js:18:19)
W20171117-21:43:55.493(1)? (STDERR)     at Object.require (D:\DEV-ML\htdocs\MeteorNix\.meteor\local\build\programs\server\boot.js:287:32)
W20171117-21:43:55.495(1)? (STDERR)     at makeInstallerOptions.fallback (packages\modules-runtime.js:651:18)
W20171117-21:43:55.499(1)? (STDERR)     at require (packages\modules-runtime.js:244:16)
W20171117-21:43:55.500(1)? (STDERR)     at collection2.js (packages/aldeed:collection2-core/collection2.js:1:345)
W20171117-21:43:55.500(1)? (STDERR)     at fileEvaluate (packages\modules-runtime.js:343:9)
W20171117-21:43:55.501(1)? (STDERR)     at require (packages\modules-runtime.js:238:16)
W20171117-21:43:55.502(1)? (STDERR)     at D:\DEV-ML\htdocs\MeteorNix\.meteor\local\build\programs\server\packages\aldeed_collection2-core.js:718:15
W20171117-21:43:55.502(1)? (STDERR)     at D:\DEV-ML\htdocs\MeteorNix\.meteor\local\build\programs\server\packages\aldeed_collection2-core.js:729:3

manually adding “tmeasday:check-npm-versions” using “meteor add tmeasday:check-npm-versions” does not help.
MeteorNix.zip

.meteor\packages

[email protected]             # Packages every Meteor app needs to have
[email protected]       # Packages for a great mobile UX
[email protected]                   # The database Meteor supports right now
[email protected]    # Compile .html files into Meteor Blaze views
[email protected]           # Reactive variable for tracker
[email protected]                 # Meteor's client-side reactive programming library

[email protected]   # CSS minifier run for production mode
[email protected]    # JS minifier run for production mode
[email protected]               # ECMAScript 5 compatibility for older browsers
[email protected]              # Enable ECMAScript2015+ syntax in app code
[email protected]            # Server-side component of the `meteor shell` command

[email protected]             # Publish all data to the clients (for prototyping)
[email protected]                # Allow all DB writes from clients (for prototyping)

aldeed:collection2-core
tmeasday:check-npm-versions

package.json

{
  "name": "MeteorNix",
  "private": true,
  "scripts": {
    "start": "meteor run"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "meteor-node-stubs": "^0.3.2",
    "simpl-schema": "^0.5.0"
  }
}

Error: doc.hasOwnProperty is not a function

I'm getting the following error, but it's a bit ambiguous to say the least, any ideas as to what might be causing this? I have only just update to the v2.x version, but I don't think it's related.

W20161206-15:16:26.523(0)? (STDERR) TypeError: doc.hasOwnProperty is not a function
W20161206-15:16:26.523(0)? (STDERR)     at [object Object].doValidate (packages/aldeed:collection2-core/collection2.js:361:13)
W20161206-15:16:26.524(0)? (STDERR)     at [object Object].Mongo.Collection.(anonymous function) [as insert] (packages/aldeed:collection2-core/collection2.js:187:25)
W20161206-15:16:26.524(0)? (STDERR)     at insertLabel (imports/api/labels/schema.js:156:28)
W20161206-15:16:26.524(0)? (STDERR)     at resolveOrError (/Users/siyfion/Git/LabelLogicLive/node_modules/graphql/execution/execute.js:473:12)
W20161206-15:16:26.525(0)? (STDERR)     at resolveField (/Users/siyfion/Git/LabelLogicLive/node_modules/graphql/execution/execute.js:459:16)
W20161206-15:16:26.525(0)? (STDERR)     at /Users/siyfion/Git/LabelLogicLive/node_modules/graphql/execution/execute.js:247:20
W20161206-15:16:26.525(0)? (STDERR)     at /Users/siyfion/.meteor/packages/promise/.0.8.8.1xgcipj++os+web.browser+web.cordova/npm/node_modules/meteor-promise/fiber_pool.js:32:39

How can i use this in a package

Hello,
I would like to construct my app by multi separated MeteorJS packages.
I would like to use and define this in a package 'namespace:lib'.
How can i define and use it in package for import SimpleSchema from 'simpl-schema'
and make the functionality to global just like we install under app (api.export)?

Thanks

MongoError: connection to DB timed out

I have an app that gets some information from an API call and then uploads the result to a collection.

I first gather all the right documents in an array then do array.map(object => Collection.insert(object));

But it throws the error below for an array of about 70 objects. Should I setTimeout on the map to insert the objects every x milliseconds or is it caused by something else?

Exception in setTimeout callback: MongoError: connection 4 to aws-us-east-1-portal.23.dblayer.com:15676 timed out
    at Object.Future.wait (/var/app/current/node_modules/fibers/future.js:449:15)
    at null.<anonymous> (packages/meteor.js:213:24)
    at null.MongoConnection.(anonymous function) [as insert] (meteor://💻app/packages/mongo/mongo_driver.js:778:49)
    at null.insert (meteor://💻app/packages/mongo/collection.js:524:37)
    at null.Mongo.Collection.(anonymous function) [as insert] (packages/aldeed_collection2-core.js:232:19)
    at meteor://💻app/imports/startup/server/analytics.js:319:13
    at null._.extend.withValue (packages/meteor.js:1122:17)
    at packages/meteor.js:445:45
    at runWithEnvironment (packages/meteor.js:1176:24)
    - - - - -
    at Function.MongoError.create (/var/app/current/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/error.js:29:11)
    at TLSSocket.<anonymous> (/var/app/current/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:186:20)
    at TLSSocket.g (events.js:260:16)
    at emitNone (events.js:67:13)
    at TLSSocket.emit (events.js:166:7)
    at TLSSocket.Socket._onTimeout (net.js:332:8)
    at _runOnTimeout (timers.js:524:11)
    at _makeTimerTimeout (timers.js:515:3)
    at Timer.unrefTimeout (timers.js:584:5)

collection.simpleSchema() requires doc argument when there are multiple schemas

I believe this commit broke functionality in some apps: 587c0f4#diff-aa20ec9593194588d778c79c8821e0d1R88

My app did not change and was successfully running these versions:

After a meteor update, these package versions are used:

    +aldeed:[email protected]
    +aldeed:[email protected]
    +aldeed:[email protected]
    +aldeed:[email protected]
    +aldeed:[email protected]
    (Also, Autoform is used but the version did not change--aldeed:[email protected])

And it throws this error:

    Error: collection.simpleSchema() requires doc argument when there are multiple schemas meteor.js:880:11

    obj.prototype.simpleSchema@http://localhost:3000/packages/aldeed_collection2-core.js?b5d04a9cee2ea469306c494b472f19e5037eb8e5:154:1
    setDefaults@http://localhost:3000/packages/aldeed_autoform.js?b3aa1a45a8c57d1da1124520538d2cb9fa458509:3013:18
    autoFormCreated/<@http://localhost:3000/packages/aldeed_autoform.js?b3aa1a45a8c57d1da1124520538d2cb9fa458509:6559:12
    viewAutorun/</<@http://localhost:3000/packages/blaze.js?695c7798b7f4eebed3f8ce0cbb17c21748ff8ba8:1880:18
    Template._withTemplateInstanceFunc@http://localhost:3000/packages/blaze.js?695c7798b7f4eebed3f8ce0cbb17c21748ff8ba8:3679:12
    viewAutorun/<@http://localhost:3000/packages/blaze.js?695c7798b7f4eebed3f8ce0cbb17c21748ff8ba8:1878:1
    Blaze._withCurrentView@http://localhost:3000/packages/blaze.js?695c7798b7f4eebed3f8ce0cbb17c21748ff8ba8:2219:12
    viewAutorun@http://localhost:3000/packages/blaze.js?695c7798b7f4eebed3f8ce0cbb17c21748ff8ba8:1877:1
    Tracker.Computation.prototype._compute@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:349:5
    Tracker.Computation@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:237:5
    ... (stack track trimmed here)

My app is using multiple schemas like this and was fully working before the dependencies update:

    Products.attachSchema(SchemaA, {selector: {type: 'a'}});
    Products.attachSchema(SchemaB,   {selector: {type: 'b'  }});

Can you give me a hint of what 'doc' parameter it is referring to please? Is this on the autoform, when attaching the schema to a collection, etc? That way I can know where to look to solve this and further test if it's an error with this package.

Collection insert method not found 404

Hi, I'm calling the mongo insert method from a container and I'm getting the error you see at the below.

The thing is, this technique worked when simple-schema and collection2 were atmosphere packages. The beauty was that collection2 allowed you to update collections without the need for Meteor.method.

So am I missing something or is this broken?

Cheers and thanks in advance.

PS: This newer way was is great because validation is baked in (no need for ValidatedMethod / Run etc)

Error on browser console

errorClass {isClientSafe: true, error: 404, reason: "Method '/surveyResults/insert' not found", details: undefined, message: "Method '/myCollection/insert' not found [404]"…}
details:undefined
error:404
errorType:"Meteor.Error"
isClientSafe:true
message:"Method '/myCollection/insert' not found [404]"
reason:"Method '/myCollection/insert' not found"

Code

Meteor: 1.5.x
colletion2-core: latest

/imports/ui/container.js

import { Meteor } from 'meteor/meteor'
import { createContainer } from 'meteor/react-meteor-data'
import MyCollection from '../../collections/MyCollection'

import Listing from './Listing'

function addToCollection(doc) {
  MyCollection.insert({doc}, (error, result) => {
      console.log("error")
      console.log(error)
      console.log("result")
      console.log(result)
    }
  )
}

const Container = createContainer( (  ) => {

  const sub = Meteor.subscribe('list')
  const loading = !sub.ready()
  const list = MyCollection.find({}).fetch()

  return {
    loading,
    list,
    addToCollection,
  }
}, Listing)

export default Container

/imports/collections/MyCollection.js

import { Mongo } from 'meteor/mongo'
import SimpleSchema from 'simpl-schema'

const MyCollection= new Mongo.Collection('myCollection')

SurveyResults.attachSchema(
  new SimpleSchema({
    something: {
      type: String,
      label: "a label",
      optional: true
    },
  })
)

export default MyCollection

how do I use this?

this is a stupid question... but I believe I followed the readme and I am trying to figure out what obvious error I am missing. Might help another n00b...

check the gist here:
https://gist.github.com/thomastraum/56a6224e35a06fbd0702e6b7bf076fc2

For some reason, things.insert is never validated.... it simply doesn't use colleciton2 at all. Its added to the project I verified a few times.

I call it via Meteor.call('things.insert', newThing ); on the client

Return ValidationError's from Meteor.methods

Hello @aldeed,

I'm just starting to work with Meteor and your package is suggested in the guides along with mdg:validated-method. The documentation stated that a ValidationError (from mdg:validation-error) would be return but after scanning the source code here this doesn't seem to be the case any more, instead it now returns a Meteor.Error with json encoded details. How I'm using these libraries together:

I have a simple collection, with a very basic schema (using npm simpl-schema):

export const Shops = new Mongo.Collection('shops')
Shops.attachSchema(new SimpleSchema({
    name: { type: String },
    createdAt: { type: Date },
    updatedAt: { type: Date }
}))

And to manipulate this collection from the client-side I created the following method:

export const insert = new ValidatedMethod({
    name: 'shops.insert',
    validate: new SimpleSchema({
        shop: { type: Object }
    }).validator(),
    run({ shop }) {
        return Shops.insert({
            ...shop,
            createdAt: new Date(),
            updatedAt: new Date()
        })
    }
})

Note that I use the validation in the method to do very basic argument checks and let Shops.insert handle the actual object validation (because I don't want the client to supply the timestamps and wouldn't like to redefine most of the schema in the ValidatedMethod).

When validation fails the client-side receives a Meteor.Error with status 400, a reason based on the failing field and json encoded details. What is the way to go here; Should I parse the details myself or can I somehow map the error to a ValidationError?

Support whole-document updates

I have a displayableLocation field which I compute via autoValue when address field is set (essentially adding random "jitter" to the provided address). I'm returning an object from autoValue like so:

displayableLocation: {
  type: Object,
  autoValue: function () {
    // other logic
    return {
      address: '...'
    }
  }
}

However when I call MapEnitites.update({_id: entity._id}, entity), autoValue adds the displayableLocation.address field under a $set modifier so I end up with a half-modifier, half-document and collection2 reports Expected '_id' to be a modifier operator like '$set'.

Can I actually use whole documents with update?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.