SimpleSchema insert fails with unhelpful error unless {validate: false} is set - meteor

At this point I've actually pared down my code to mimic the example in the docs, and I'm getting the same error.
I've defined my Collection as such:
var Categories = new Mongo.Collection('categories');
const CategorySchema = new SimpleSchema({
title: {
type: String,
label: "Title",
max: 255,
optional: true
},
created: {
type: Date,
label: "Date Category Created",
autoValue: () => {
if(this.isInsert){
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
}
}
},
updated: {
type: Date,
label: "Date Category Modified",
autoValue: () => {
if(this.isUpdate){
return new Date();
}
},
optional: true
}
});
Categories.attachSchema(CategorySchema);
export { Categories };
The autovalue stuff is borrowed straight from the docs.
And have a method for calling insert:
Meteor.methods({
'categories.insert'(title){
check(title, String);
Categories.insert({title: title}, (err, res) => {
if(err){
console.error("Category insert failed: " + err);
}
});
},
...
As I've tried to get through this issue, I've added and removed rules to the schema definition, sometimes getting a call stack exceeded error. Mostly what I get is the following:
Exception while simulating the effect of invoking 'categories.insert' TypeError: func is not a function
at http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:13027:18
at Array.forEach (native)
at doValidation (http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:13026:17)
at ValidationContext.validate (http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:12580:57)
at ns.Collection.doValidate (http://localhost:3000/packages/aldeed_collection2-core.js?hash=0564817159bbe9f8209b6a192a1fa2b2bbab924a:466:33)
at ns.Collection.Mongo.Collection.(anonymous function) [as insert] (http://localhost:3000/packages/aldeed_collection2-core.js?hash=0564817159bbe9f8209b6a192a1fa2b2bbab924a:260:25)
at ns.Collection.<anonymous> (http://localhost:3000/packages/matb33_collection-hooks.js?hash=d44fd0eb02806747e1bb0bdc3938463e415c63ec:402:19)
at ns.Collection.collection.(anonymous function) [as insert] (http://localhost:3000/packages/matb33_collection-hooks.js?hash=d44fd0eb02806747e1bb0bdc3938463e415c63ec:155:21)
at DDPCommon.MethodInvocation.categories.insert (http://localhost:3000/app/app.js?hash=580bf82f2f196202280f32cf5ffacbc930cd6b10:20073:14)
at http://localhost:3000/packages/ddp-client.js?hash=c9ca22092a3137a7096e8ab722ba5ab8eedb9aec:4076:25 TypeError: func is not a function
at http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:13027:18
at Array.forEach (native)
at doValidation (http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:13026:17)
at ValidationContext.validate (http://localhost:3000/packages/modules.js?hash=fefb674368e70344875cb9448e3ea784a880ffb0:12580:57)
at ns.Collection.doValidate (http://localhost:3000/packages/aldeed_collection2-core.js?hash=0564817159bbe9f8209b6a192a1fa2b2bbab924a:466:33)
at ns.Collection.Mongo.Collection.(anonymous function) [as insert] (http://localhost:3000/packages/aldeed_collection2-core.js?hash=0564817159bbe9f8209b6a192a1fa2b2bbab924a:260:25)
at ns.Collection.<anonymous> (http://localhost:3000/packages/matb33_collection-hooks.js?hash=d44fd0eb02806747e1bb0bdc3938463e415c63ec:402:19)
at ns.Collection.collection.(anonymous function) [as insert] (http://localhost:3000/packages/matb33_collection-hooks.js?hash=d44fd0eb02806747e1bb0bdc3938463e415c63ec:155:21)
at DDPCommon.MethodInvocation.categories.insert (http://localhost:3000/app/app.js?hash=580bf82f2f196202280f32cf5ffacbc930cd6b10:20073:14)
at http://localhost:3000/packages/ddp-client.js?hash=c9ca22092a3137a7096e8ab722ba5ab8eedb9aec:4076:25
meteor.js?hash=27829e9…:930 Error invoking Method 'categories.insert': Internal server error [500]
EDIT
After swapping out the arrow functions:
methods.js
Meteor.methods({
// Settings: create new category
'categories.insert': function(title){
check(title, String);
Categories.insert({title: title}, function(err, res){
if(err){
console.error("Category insert failed: " + err);
}
});
},
...
settings.js
Template.settings.onCreated(function(){
Meteor.subscribe('categories');
});
Template.settings.helpers({
categories: function(){
return Categories.find();
}
});
Template.settings.events({
'click #newCategoryButton': function(e){
let title = $("#newCategoryInput").val();
if(title !== ""){
Meteor.call('categories.insert', title);
$("#newCategoryInput").val("").focus();
}
},
'click .removeCategory': function(e){
var id = $(e.currentTarget).data('id');
Meteor.call('categories.remove', id);
}
});
Categories.js
var Categories = new Mongo.Collection('categories', options);
const CategorySchema = new SimpleSchema({
title: {
type: String,
label: "Title",
max: 255,
optional: true
},
created: {
type: Date,
label: "Date Category Created",
autoValue: function(){
if(this.isInsert){
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
}
}
},
updated: {
type: Date,
label: "Date Category Modified",
autoValue: function(){
if(this.isUpdate){
return new Date();
}
},
optional: true
}
});
Categories.attachSchema(CategorySchema);
Still getting the same error as in original post

You're using arrow functions like Sean mentioned in the comment. Replace them with traditional function(){...} and you should be good to go.
You can read more about this issue here

Related

DynamoDb Update an Item from Node.js

I had the following code which originally worked for creating a user.
var params = {
TableName: 'myproject-user',
Item: {
id: req.body.userName,
email: req.body.email
}
};
if(req.body.currency) {
params.Item.currency = {
type: req.body.currency.type,
bank: req.body.currency.bank,
amount: req.body.currency.amount,
}
}
docClient.put(params, function(err, data) {
if (err) {
res.send({
success: false,
message: 'Error: ' + err
});
} else {
const { Items } = data;
res.send({
success: true,
message: 'Added user',
email: req.body.email
});
}
});
I'm now switching to put to update, as I want to be able to keep any existing values on the object while updating the email or name. In addition I have added the following line in the params object to specify the key which is id.
Key: { id : req.user.sub },
The doc.update code executes and I get back status 200 as if there was no problem, but when I look at the table the information hasn't been updated.
Do I need to use an expression or something to get update to work?
Code with changes:
var params = {
TableName: 'myproject-user',
Key: {"id":req.user.sub},
Item: {
id: req.body.userName,
email: req.body.email
}
};
docClient.update(params, function(err, data) {
if (err) {
res.send({
success: false,
message: 'Error: ' + err
});
} else {
const { Items } = data;
res.send({
success: true,
message: 'Added user',
email: req.body.email
});
}
});
I was able to get this working by using UpdateExpression, ExpressionAttributeValues, and ReturnValues attributes instead of Item, as described here:
var params = {
TableName: 'krncdev-user',
Key: {"id":req.user.sub},
UpdateExpression: "set email=:e",
ExpressionAttributeValues:{
":e": req.body.email
},
ReturnValues:"UPDATED_NEW"
};

Cannot insert relationship ID into Aldeed's Autoform MeteorJS framework

New to MeteorJS. I started making a novel Clan/Samurai app to see if I could understand how mongo/meteor and Autoforms handle relationships. I'm trying to make clans and samurai relate to each other so that each Samurai has a specific clan.
I'm attempting to insert the clan data into the Samurai identity. I seem to not be able to.
I've read the following and still seem generally confused on how to implement this. I've tried before, onsuccess, onsubmit hooks. I've attempted to set the schema up so that it works. I mostly get AutoForm undefined or Schema undefined...tons of errors it seems. I've read that it should be client.
I can console log and get it to render but I can't add the new items to the collection.
Random Github made for viewing pleasure
https://github.com/qtheninja/SamuraiAttack
https://github.com/aldeed/meteor-collection2/issues/31
How to add a relationship or reference with AutoForm in Meteor?
Meteor Autoform package with collection2 does not submit the form
//lib/collections/clans.js
Clans = new Mongo.Collection('clans');
Clans.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Clan Name",
max: 100
}
}));
if (Meteor.isServer) {
Clans.allow({
insert: function (userId, doc) {
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
}
//lib/collections/samurais.js
Samurais = new Mongo.Collection('samurais');
Samurais.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 100
},
description: {
type: String,
label: "Description",
optional: true
},
clan: {
type: Clans
}
}));
if (Meteor.isServer) {
Samurais.allow({
insert: function (userId, doc) {
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
}
//client/template/clans/createClan.html
<template name="CreateClan">
<h1>Create New Clan</h1>
{{> quickForm
collection="Clans"
id="insertClanForm"
type="insert"
buttonContent="Create"
}}
<div>
{{> ListClans }}
</div>
</template>
//client/main.js
AutoForm.addHooks('insertSamuraiForm', {
before: {
insert: function(doc, template) {
//modify the document here
doc.clanid= 45;
doc.dance ="start again";
console.log("running after hook");
return true;
}
}
});
AutoForm.hooks({
insertSamuraiForm: {
before: {
insert: function(doc, template) {
//modify the document here
doc.projectid= "random";
doc.dance ="start again";
console.log('this is asecond form');
}
}
}
});
I was able to resolve this issue by doing the following.
Return on object using 'before' hook
Router.current().params._id
a. I was using iron router and in my url was clans/_id/samurai/new
added 'dance' and 'clanid' as apart of the simpleschema. I had neglected to include them as apart of the schema so I was getting the console.log to work but not the data to be apart of the object.
//client/lib/main.js (alterations)
before: {
insert: function(doc, template) {
//modify the document here
doc.clanid= Router.current().params._id;
doc.dance ="start again";
console.log("running after hook");
return doc;
}
}
//lib/collections/samurais.js
Samurais = new Mongo.Collection('samurais');
Samurais.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 100
},
description: {
type: String,
label: "Description",
optional: true
},
clanid: {
type: String,
label: "ignore this",
optional: true
},
dance: {
type: String,
optional: true
}
}));
if (Meteor.isServer) {
Samurais.allow({
insert: function (userId, doc) {
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
}

Need help updating Router.js for upgrade to Meteor 1.0 and iron:router package

I'm in the midst of updating from Meteor 8.2 to Meteor 1.0. I've removed all my old meteorite packages and installed the relevant meteor package system packages. I had to install the new iron-router package and I'm getting the following error in my console on meteor run:
Route dispatch never rendered. Did you forget to call this.next() in an onBeforeAction?
The migration notes for the package say: "onBeforeAction hooks now require you to call this.next(), and no longer take a pause() argument."
I tried following the example by remove pause from the function and adding this.next(); after the else statement, but to no avail.
How to edit my router so it uses the new onBeforeAction hook? Also, anything else you can call out from the migration that might be problematic would be much appreciated. Thanks!
Here's my router file:
/*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
// TODO: use these as per the Event Mind CLI tool.
//Router.configure({
// templateNameConverter: 'upperCamelCase',
// routeControllerNameConverter: 'upperCamelCase'
//});
Router.configure({
layoutTemplate: 'devLayout',
notFoundTemplate: 'devMain',
loadingTemplate: 'loading'
});
Router.onRun(function () {Session.set("waiting-on", null); });
Router.onBeforeAction(function() { Alerts.clearSeen(); });
var filters = {
nProgressHook: function (pause) {
// we're done waiting on all subs
if (this.ready()) {
NProgress.done();
} else {
NProgress.start();
pause(); // stop downstream funcs from running
}
}
};
Router.onBeforeAction(filters.nProgressHook);
Meteor.startup(function () {
Router.map(function () {
this.route('loading');
// reset password urls use hash fragments instead of url paths/query
// strings so that the reset password token is not sent over the wire
// on the http request
this.route('reset-password', {
template: 'devMain',
layoutTemplate: 'devLayout',
onRun: function () {
var token = this.params.hash;
Meteor.logout(function () {
Session.set("viewing-settings", true);
Session.set("set-password-token", token);
Session.set("settings-set-password", true);
// Session.set("enrolling", true) // do something special?
});
}
});
this.route('verify-email', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Accounts.verifyEmail(token, function (err) {
if (!err) {
Alerts.throw({
message: "Your email address is now verified!",
type: "success", where: "main",
autoremove: 3000
});
Router.go('home');
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason +
"\". Try again?",
type: "danger", where: "main"
});
Session.set("viewing-settings", true);
Router.go('home');
}
});
}
});
this.route('leave-game', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("leaveGameViaToken", token, function (err, res) {
if (!err) {
// Idempotently verify user's email,
// since they got the token via email.
Accounts.verifyEmail(token);
if (res.error) {
// e.g. "Leave-game link is for unknown game"
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, you are no longer in this game.",
type: "success", where: res.gameId
});
Router.go("devDetail", {_id: res.gameId});
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
this.route('game-on', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("gameOnViaToken", token, function (err, res) {
if (err || (res && res.error)) {
errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;
Alerts.throw({
message: errorMessage, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "Woohoo! Players will be notified.",
type: "success", where: res.gameId
});
Router.go("devDetail", {_id: res.gameId, token: token });
}
});
}
});
this.route('cancel-game', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("cancelGameViaToken", token, function (err, res) {
if (!err) {
Accounts.verifyEmail(token);
if (res.error) {
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, your game is now cancelled, and players "
+ "will be notified.",
type: "success", where: "main"
});
Router.go("home");
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
// quite similar to 'leave-game' route
this.route('unsubscribe-all', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("unsubscribeAllViaToken", token, function (err, res) {
if (!err) {
// Idempotently verify user's email,
// since they got the token via email.
Accounts.verifyEmail(token);
if (res.error) {
// e.g. "Token provided in link is not an unsubscribe-all token"
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, you will no longer receive emails "
+ "from Push Pickup.",
type: "success", where: "main"
});
Router.go("home");
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
this.route('enroll-account', {
template: 'devMain',
layoutTemplate: 'devLayout',
onRun: function () {
var token = this.params.hash;
Meteor.logout(function () {
Session.set("viewing-settings", true);
Session.set("set-password-token", token);
Session.set("settings-set-password", true);
// Session.set("enrolling", true) // do something special?
});
}
});
// the home page. listing and searching for games
this.route('home', {
path: '/',
template: 'devMain',
layoutTemplate: 'devLayout'
});
// typical user interaction with a single game
this.route('devDetail', {
path: '/g/:_id/:token?',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("joined-game", null);
},
waitOn: function () {
return Meteor.subscribe('game', this.params._id);
},
onBeforeAction: function (pause) {
Session.set("soloGame", this.params._id);
},
data: function () {
var game = Games.findOne(this.params._id);
if (game) {
Session.set("gameExists", true);
}
return game;
},
action: function () {
var token = this.params.token;
if (Session.get("gameExists")) {
this.render();
} else {
Router.go('home');
Alerts.throw({
message: "Game not found",
type: "warning", where: "top"
});
}
if (token) {
Meteor.call("sendReminderEmailsViaToken", token, function (err, res) {
var errorMessage;
Accounts.verifyEmail(token);
if (err || (res && res.error)) {
errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;
Alerts.throw({
message: errorMessage, type: "danger", where: "main"
});
Router.go("home");
}
});
}
},
onStop: function () {
Session.set("soloGame", null);
Session.set("gameExists", null);
}
});
this.route('devAddGame', {
path: '/addGame',
template: 'devEditableGame',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("selectedLocationPoint", null);
Session.set("newGameDay", null);
Session.set("newGameTime", null);
InviteList.remove({});
},
waitOn: function() {
Meteor.subscribe('recently-played');
},
data: function () {
return {
action: 'add',
title: 'Add game',
submit: 'Add game'
};
}
});
this.route('invitePreviousPlayers', {
path: 'invitePlayers',
template: 'invitePreviousPlayers',
layoutTemplate: 'devLayout'
});
this.route('devEditGame', {
path: '/editGame/:_id',
template: 'devEditableGame',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("selectedLocationPoint", null);
},
waitOn: function () {
return Meteor.subscribe('game', this.params._id);
},
onBeforeAction: function (pause) {
Session.set("soloGame", this.params._id);
},
data: function () {
return _.extend({
action: 'edit',
title: 'Edit game',
submit: 'Update game'
}, Games.findOne(this.params._id));
},
action: function () {
var self = this;
var user = Meteor.user();
var game = self.data();
if (user && user._id === game.creator.userId ||
user && user.admin) {
self.render();
} else {
Router.go('home');
}
}
});
this.route('adminView', {
path: '/admin',
onBeforeAction: function () {
var user = Meteor.user();
if (!user || !user.admin) {
this.render('home');
}
}
});
});
});
New onBeforeAction hook must call this.next(); You must call it in every onBeforeAction. For example your admin route in new Iron Router would look like this:
Router.route('/admin', {
name: 'adminView',
onBeforeAction: function () {
var user = Meteor.user();
if (!user || !user.admin) {
this.render('home');
}
this.next();
}
});
Replace all this.route(...) in Router.map with Router.route('/path', options) and remove Router.map()
Your global onBeforeAction will look like this:
Router.onBeforeAction(function() {
Alerts.clearSeen();
this.next();
});
Also, you don't need to wrap your routes in Meteor.startup(...). You can remove it.
And there is no pause parameter anymore, instead of pause call this.next() outside condition:
var filters = {
nProgressHook: function () {
// we're done waiting on all subs
if (this.ready()) {
NProgress.done();
} else {
NProgress.start();
}
this.next();
}
};
Router.onBeforeAction(filters.nProgressHook);

Meteor.js collection aggregate returning undefined is not a function

I am trying to make collection aggregate in my Meteor.js app as shown below, yet each time I call my server logSummary method I get the following error. Can someone please tell me what I am doing wrong / how to resolve this error? Thanks.
Note: I am using Meteor-aggregate package
TypeError: undefined is not a function
at Object.Template.detailedreport.helpers.myCollection (http://localhost:3000/client/views/report.js?
Code:
Template.detailedreport.rendered = function() {
Session.set("dreport_customer", "");
Session.set("dreport_project", "");
Session.set("dreport_startDate", new Date());
Session.set("dreport_endDate", new Date());
$('.set-start-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-end-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-start-date').on("dp.change",function (e) {
Session.set("dreport_startDate", $('.set-start-date').data('DateTimePicker').getDate().toLocaleString());
});
$('.set-end-date').on("dp.change",function (e) {
Session.set("dreport_endDate", $('.set-end-date').data('DateTimePicker').getDate().toLocaleString());
});
};
Template.detailedreport.helpers({
customerslist: function() {
return Customers.find({}, {sort:{name: -1}});
},
projectslist: function() {
return Projects.find({customerid: Session.get("dreport_customer")}, {sort:{title: -1}});
},
myCollection: function () {
var now = Session.get("dreport_startDate");
var then = Session.get("dreport_endDate");
var custID = Session.get("dreport_customer");
var projID = Session.get("dreport_project");
Meteor.call('logSummary', now, then, projID, custID, function(error, data){
if(error)
return alert(error.reason);
return data;
});
},
settings: function () {
return {
rowsPerPage: 10,
showFilter: true,
showColumnToggles: false,
fields: [
{ key: '0._id.day', label: 'Day' },
{ key: '0.totalhours', label: 'Hours Spent'}
]
};
}
});
Template.detailedreport.events({
'submit form': function(e) {
e.preventDefault();
Session.set('dreport_endDate', $('.set-end-date').data('DateTimePicker').getDate().toLocaleString());
Session.set('dreport_startDate', $('.set-start-date').data('DateTimePicker').getDate().toLocaleString());
Session.set('dreport_project', $(e.target).find('[name=project]').val());
Session.set('dreport_customer', $(e.target).find('[name=customer]').val());
},
'change #customer': function(e){
Session.set("dreport_project", "");
Session.set("dreport_customer", e.currentTarget.value);
},
'change #project': function(e){
Session.set("dreport_project", e.currentTarget.value);
}
});
Template:
<div>
{{> reactiveTable class="table table-bordered table-hover" collection=myCollection settings=settings}}
</div>
Server:
Meteor.methods({
logSummary: function(startDate, endDate, projid, custid){
var pipeline = [
{ $match: { date: { $gte: new Date(startDate), $lte: new Date(endDate) },
projectid: projid,
customerid: custid
}
},
{ $group: {
_id: {
"projectid": "$projectid",
"day": { "$dayOfMonth": "$date" },
"month": { "$month": "$date" },
"year": { "$year": "$date" }
},
totalhours: {"$sum": "$hours"}
}}
];
return ProjectLog.aggregate(pipeline);;
}
});
Looking at the ReactiveTable documentation, it looks like you need to do something like:
Template.myTemplate.helpers({
myCollection: function () {
return myCollection;
}
});
Where myCollection is the name of a Mongo/Meteor collection (e.g. BlogPosts) which you defined with e.g. BlogPosts = new Mongo.Collection('blogPosts');
The reason you're getting undefined is not a function is that you are calling a Meteor method inside a template helper. The call is asynchronous so the return value is undefined. Now you are passing undefined to ReactiveTable. ReactiveTable will be trying to call something like myCollection.find() which is essentially undefined.find() and will therefore throw the error you're seeing.
Later on the Meteor call will finish and the data value will be lost because the function has already returned.
You can call Meteor.call inside the onCreated function like so:
Template.myTemplate.onCreated(function () {
Meteor.call('myFunction', 'my', 'params', function (err, result) {
if (err) {
// do something about the error
} else {
Session.set('myData',result);
}
});
});
Template.myTemplate.helpers({
myData: function () {
Session.get('myData')
}
});
This won't fix the issue with ReactiveTable, however.
If the collection you're trying to display is only used for this single page, you could put the aggregation inside the publish function so that minimongo contains only the documents that match the aggregation and therefore the correct documents will appear in your ReactiveTable.

FS.Collection Image ID don't validate check()

I'm trying to save image id after insert in FS.Collection.
Insert array
var item = {
name: $(value).find('#name').val(),
article: $(value).find('#article').val(),
description: $(value).find('#description').val(),
price: $(value).find('#price').val(),
sizes: $(value).find('#sizes').val()
};
file = $(value).find('#attachmentName')[0].files[0];
if (file !== undefined) {
Images.insert(file, function (err, fileObj) {
item = _.extend(item, {
image: fileObj._id.toString()
});
});
}
Meteor.call('collectionInsert', item, function(error, result) {
if (error)
return alert(error.reason);
Router.go('collection', {_id: result._id});
});
collectionInsert method
Meteor.methods({
collectionInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
name: String,
article: String,
description: String,
price: String,
sizes: String,
image: String
});
var user = Meteor.user();
var post = _.extend(postAttributes, {
userId: user._id,
author: user.profile.name,
timestamp: new Date(),
views: 0
});
var collectionId = Collections.insert(post);
return {
_id: collectionId
};
}
});
Then i'm got Exception
Exception while invoking method 'collectionInsert' Error: Match error: Missing key 'image'
In console log i have item value
...
image: "4J55dyGb5DpqbCXGG"
...
I'm trying to change check property to image: Match.Optional([String]) and image: Match.Any - no effect
I think the issue here is that your insert method is non-blocking, which means that you probably haven't received the fileObj nor extended item before passing it to the method call. Maybe you should try to make the method call in the insert callback, like this:
if (file !== undefined) {
Images.insert(file, function (err, fileObj) {
item.image = fileObj._id.toString(); // don't need _.extend
// item should now be extended
Meteor.call('collectionInsert', item, function(error, result) {
if (error)
return alert(error.reason);
Router.go('collection', {_id: result._id});
});
});
}
By the way, you should probably store the result of $(value) instead of constructing the same jQuery object over and over. Just a minor optimization, but improves readability nonetheless.
var $value = $(value);
var item = {
name: $value.find('#name').val(),
...
};

Resources