Meteor. Problems with subscribe/publish - meteor

i have a problem.
I'm trying to build highcharts graphic.
How it works:
I'm going to my route ('ship.details'), and here i have not problems.
My problem:
subsription to (ships_snapshots_all) not working.
My publish.js:
Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
}
});
Meteor.publish("ships_snapshots_all", function() {
return ships_snapshots.find({});
})
My subscribe.js (in lib folder):
Meteor.subscribe('ships_snapshots');
Meteor.subscribe('ships_snapshots_all');
Problem 100% in my subsription, because if i'm installing autopublish all working good. And problem in my router i think.
router.js:
Router.route('/ships/details', {
name: 'ship.details',
loadingTemplate: 'loading',
onBeforeAction: function() {
var shipId = Session.get('currentShipId');
if(!shipId) {
Router.go('user.ships');
} else {
this.next();
}
},
waitOn: function() {
if (Meteor.isClient) {
var getCompare = Meteor.user().profile.wows.compareWith;
console.log(getCompare);
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
var user2Id = user2._id;
if (getCompare) {
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
if (user2) {
var user2Id = user2._id;
}
}
if (getCompare) {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id) && Meteor.subscribe('userSearchInfo', getCompare);
Session.set('compareWith', user2);
console.log('user2 _____');
console.log(user2);
return handle
} else {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id);
return handle
}
}, data: function() {
if (handle.ready()) {
var shipname = this.params.shipName;
var obj = {};
var query = ships.findOne();
var shipId = Session.get('currentShipId');
var result;
_.each(Meteor.user().profile.wows.ships, function(row) {
if (row.ship_id === shipId) {
result = row;
}
});
return result;
}
}
});
I think my problem in subscripion for ship_snapshots. Something going wrong here, but i can't to resolve this problem.

What exactly do you mean by "not working"? From your code I would assume that you're always seeing all the ship snapshots.
You shouldn't have the subscribes in /lib if you have them in your router. If you have Meteor.subscribe('ships_snapshots_all'); in /lib then you should always be seeing all the ship snapshots (assuming you're not stopping that subscription anywhere).
Also your subscription to all should be:
Meteor.publish("ships_snapshots", function(user, options) {
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
} else this.ready();
});
You don't want to return null when there is no user, you can just mark the subscription as ready without finding any records. This is not the cause of your problem but just good practice.

Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user._id}, options);
}
});
In your publish script, is user really an id or is it a user object? I changed it to user._id. Please check that.

Related

Meteor.call and server methods not working properly

I have this code on my meteor app:
// client side
Template.lead.events({
'submit .insertExternalAccountForm': function (event) {
event.preventDefault();
Session.set('mcsStatus', 'Creating external account ...');
var target = {
code: event.target.code.value,
leadId: event.target.leadId.value,
name: event.target.name.value,
username: event.target.username.value,
password: event.target.password.value,
searchSourceId: event.target.searchSourceId.value,
clientId: event.target.clientId.value,
clientUserId: event.target.clientUserId.value
};
var noFormError = true;
if (target.username.length === 0) {
Session.set("username_error", "Field must not be empty");
noFormError = false;
} else {
Session.set("username_error", null);
}
if (target.password.length === 0) {
Session.set("password_error", "password must not be empty");
noFormError = false;
} else {
Session.set("password_error", null);
}
if (!noFormError) {
return noFormError;
}
Meteor.call('createExternalAccount', target, function (err, res) {
if (err) {
console.error(err);
}
console.log('in meteor call');
Router.go('/' + res.domain + '/' + res.externalId);
});
}
});
//server side
var createExternalAccountSync = function (query, external) {
return models.SearchSources.findOne(query).exec()
.then(function (searchsource) {
external.domain = searchsource.source;
var emr = searchsource.source.split('-');
return models.Organization.findOne({externalId: emr[2]}).exec();
}).then(function (org) {
console.log('after org');
external.organizationId = org._id;
return models.AppUser.findOne({clientId: external.clientId, externalId: external.clientUserId }).exec();
}).then(function (user) {
console.log('after app user');
external.userId = user._id;
external.userIds = [user._id];
return new Promise(function (resolve,reject) {
console.log('saveOrUpdate');
models.ExternalAccount.saveOrUpdate(external, function (err, newE) {
if (err) {
console.error(err)
reject(err);
}
resolve(newE)
});
});
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
};
Meteor.methods({'createExternalAccount': function (data) {
var query = {};
var newExternalAccount = new models.ExternalAccount();
newExternalAccount.username = data.username;
newExternalAccount.password = data.password;
newExternalAccount.externalId = data.username;
newExternalAccount.name = data.name;
newExternalAccount.clientId = data.clientId;
newExternalAccount.clientUserId = data.clientUserId;
newExternalAccount._metadata = { leadId: data.leadId };
if (data.code === 'f') {
query.searchSourceId = '5744f0925db77e3e42136924';
} else {
query.searchSourceId = data.searchSourceId;
}
newExternalAccount.searchSourceId = query.searchSourceId;
console.log('creating external account')
createExternalAccountSync(query, newExternalAccount)
.then(function (external) {
console.log('should return to meteor call');
return external;
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
}
});
The problem that I'm having is that the code on the server side, while it's being called properly, is not triggering the client side meteor.call, there's no console.log output or anything. I believe that the Meteor.wrapAsync method is properly used, but still not showing anything on the client side, and not in fact redirecting where I want the user to go after form submission.
UPDATE
The code has being updated to the newest form, but now I'm getting a weird error on the client, and its actually because the meteor.call method on the template returns neither error or result
Exception in delivering result of invoking 'createExternalAccount': http://localhost:3000/app/app.js?hash=c61e16cef6474ef12f0289b3f8662d8a83a184ab:540:40
http://localhost:3000/packages/meteor.js?hash=ae8b8affa9680bf9720bd8f7fa112f13a62f71c3:1105:27
_maybeInvokeCallback#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3557:21
receiveResult#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3577:30
_livedata_result#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:4742:22
onMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3385:28
http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2736:19
forEach#[native code]
forEach#http://localhost:3000/packages/underscore.js?hash=27b3d669b418de8577518760446467e6ff429b1e:149:18
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2735:15
dispatchEvent#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:175:27
_dispatchMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1160:23
_didMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1218:34
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1365:28
By the code you provided,it could be because you are calling different method.
You defined 'createAccount' but on client side you are calling 'createExternalAccount'

CollectionFS 503 Service Unavailable

I need to upload 'on fly' user's image. But i get error 503 Service Unavailable.
user.js
Meteor.subscribe('userImages');
Template.userProfil.events({
'change [name=userPhotoUpload]': function(event) {
event.preventDefault();
FS.Utility.eachFile(event, function(file) {
var newFile = new FS.File(file);
newFile.metadata = {
createdBy:Meteor.userId(),
}
userImages.insert(newFile, function (err, fileObj) {
if (err){
// handle error
} else {
// handle success depending what you need to do
var currentUserId = Meteor.userId();
var imagesURL = {
"profile.userImg": '/cfs/files/userImages/' + fileObj._id + '/' + fileObj.name()
};
Meteor.users.update(currentUserId, {$set: imagesURL});//there I get url and
}
});
});
}
});
router.js
Router.route('/organizer', {
name: 'userProfil',
template: 'userProfil',
data: function() {
var currentUser = Meteor.userId();
return Meteor.user({_id: currentUser});
}
});
user-img.html
<img src="{{profile.userImg}}">
after uploding image i get this err:
http://localhost:3000/cfs/files/userImages/wNjvF8uuN8j6fd8md/exampl2.jpg 503 (Service Unavailable)
But this path is absolutely correct, and after manual reloading page it's work.
How can I solve this problem?
Ok, I found some solution, but I don't think that it's correct way. Maybe someone have better decision?
Changing:
user.js
'change [name=userPhotoUpload]': function(event) {
event.preventDefault();
FS.Utility.eachFile(event, function(file) {
var newFile = new FS.File(file);
newFile.metadata = {
createdBy:Meteor.userId(),
}
userImages.insert(newFile, function (err, fileObj) {
if (err){
// handle error
} else {
var currentUserId = Meteor.userId();
var intervalHandle = Meteor.setInterval(function () {
console.log("Inside interval");
// changes here:
if (fileObj.hasStored("userImages")) {
//checked if image was stored
var imagesURL = {
"profile.userImg": '/cfs/files/userImages/' + fileObj._id + '/' + fileObj.name()
};
Meteor.users.update(currentUserId, {$set: imagesURL});
// if file has stored, stop interval
Meteor.clearInterval(intervalHandle);
}
}, 1000);
}
});
});
}

Weird undefined error on server

I have the following meteor method
hasNoPendingPayments: function() {
var userId = Meteor.userId();
console.log(userId); <---------------------- correctly logs userId
var user = Users.findOne({_id: userId }, { fields: { services: 0 } });
console.log(user); <-------------------------- logs 'undefined'
return hasNoPendingPayments(user);
},
This private helper I call from the above
hasNoPendingPayments = function(user) {
// console.log('hasNoPendingPayments ');
// console.log(user);
var payments = Payments.find({ userId: user._id, status: {
$in: [Payments.States.PENDING, Payments.States.PROCESSING]}
});
return payments.count() === 0;
};
And I call it from the client here
Template.payments.created = function() {
this.hasNoPendingPayments = new ReactiveVar(false);v
};
Template.payments.rendered = function () {
Session.set('showPaymentRequestForm', false);
var self = this;
Meteor.call('hasNoPendingPayments', function(error, result) {
if (result === true) { self.hasNoPendingPayments.set(true); }
});
...
However, I get an undefined error on the server when I load the template initially (I marked where in code). Although, when I try call the same query on the client with the same userId, i correctly gets the user record
Any idea as to why this is?
Try with this.
Template.payments.rendered = function () {
Session.set('showPaymentRequestForm', false);
var self = this;
if(Meteor.userId()){
Meteor.call('hasNoPendingPayments', function(error, result) {
if (result === true) { self.hasNoPendingPayments.set(true); }
});
}else{
console.log("Seems like user its not logged in at the moment")
}
Maybe when you make the Meteor.call, the data its not ready
Also just to be sure, when you run Users.findOne({_id: userId }, { fields: { services: 0 } }); on console.log what you get?
Maybe the find is wrong or have some typo
update
Router.map(function()
{
this.route('payments',
{
action: function()
{
if (Meteor.userId())
this.render();
} else{
this.render('login') // we send the user to login Template
}
}
}
or waitOn
Router.map(function () {
this.route('payments', {
path: '/payments',
waitOn: function(){
return Meteor.subscribe("userData"); //here we render template until the subscribe its ready
}
});
});
Meteor stores all the user records in Meteor.users collection
so try Meteor.users.findOne({_id: userId }....)
Instead of Users.findOne({_id: userId }, { fields: { services: 0 } });
in your server method

Meteor External API calls works but client gets Undefined

Client Side:
Template.storeInfo.events({
'click #btn-user-data': function(e) {
Meteor.call('callApi', function(err, data) {
$('#result').text(JSON.stringify(data, undefined, 4));
console.log(data); //Not working!!
});
}
});
Server Side:
storeApi.prototype.retrieve = function(endpoint) {
try {
var gotiye = HTTP.get(endpoint);
console.log(gotiye); //Works!
return gotiye;
} catch (err) {
throw new Error("Failed to fetch call GET retrieve from store. " + err.message);
}
};
storeApi.prototype.getStoreInfo = function() {
var url = this.rootApiUrl.replace(this.endpointToken,
this.endpoints.store);
this.retrieve(url);
};
Meteor.methods({
callApi: function() {
var stnvy = new storeApi(Meteor.user().services.store.accessToken);
var data = stnvy.getStoreInfo();
return data;
}
});
Why it works on server side but impossible to use in client side? Is collection the only way to use this?
Forgot to return it at getStoreInfo function return this.retrieve(url); and it works! :)

Meteor data not inserting or displaying after removing insecure package

Data is not getting inserted into the database after i removed autopublish and insecure packages. Please let me know what i am missing.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (){
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name}
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
You don't have an insert statement.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (e){
e.preventDefault(); // to prevent default action of the button
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name};
Userdata.insert(doc); // actually inserting the document
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}

Resources