Meteor - insert failed: Method not found - meteor

I have a problem with my Meteor's JS file. I get this error "insert failed: Method not found" when I try to insert any data to the database and reflect on chart. I've tried fetching data directly from db that didn't work too...
thanx in advance.
LinePeople = new Mongo.Collection("LinePeople");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
if (Meteor.isClient) {
console.log("in LIne Client");
//LinePeople = new Mongo.Collection(null);
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
chart.update();
});
};
Template.linenvd3.events({
'click #addDataButton': function() {
console.log(" in line addButton");
var age = getRandomInt(13, 89);
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
console.log(" in lastPerson.. if block");
LinePeople.insert({x:(lastPerson.x + 1), y:age});
} else {
console.log(" in lastPerson.. else block");
LinePeople.insert({x:1, y:age});
}
},
'click #removeDataButton': function() {
console.log(" in line removeButton");
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
LinePeople.remove(lastPerson._id);
}
}
});
}
if (Meteor.isServer) {
console.log("in line Server");
}

While following the Getting Started tutorial on the official meteor.js website I've had the same problem with autopublish turned on.
Turned out the issue was I created my Tasks collection inside the imports/ folder. Thus it was not implicitly imported on the server.
I had to explicitly import it on the server to solve the issue.
server/main.js
import { Meteor } from 'meteor/meteor';
import '../imports/api/tasks.js';
Meteor.startup(() => {
// code to run on server at startup
});
As you can see the import is not used by my code but is required anyways.

Thanks for the help... I actually got it worked by publishing the collection and giving it some permissions:
This code is placed in "myapp/shared/collections.js". (Placed them separately to handle all the other collections which I would add for other graphs)
lineVar = new Meteor.Collection("linenvd3");
lineVar.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
This code is placed in "myapp/server/publish.js"
Meteor.publish('line', function () {
return lineVar.find();
});
Then, this is modified Javascript made look more simpler and comprehensive.
if (Meteor.isClient) {
Meteor.subscribe('line');
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80})
.useInteractiveGuideline(true)
.transitionDuration(350)
.showLegend(true)
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]).call(chart);
chart.update();
});
};
}

Related

Can't able to fetch the user location in meteor

I developed a meteor app in which while registering I am fetching the user location at the client side, to do so I have added the packages listed below:
meteor add mdg:geolocation
meteor add jeremy:geocomplete
meteor aldeed:geocoder
meteor add jaymc:google-reverse-geocode
The code written at client side is as follows:
if (Meteor.isClient) {
Meteor.startup(() => {
GoogleMaps.load({
v: '3.26',
key: '',
libraries: 'geometry,places'
});
console.log("is GoogleMaps.loaded",GooglMaps.loaded());
});
Template.Registration.onRendered(function () {
Tracker.autorun(() => {
if (GoogleMaps.loaded()) {
$('#txt_address').geocomplete({country: "AU", type:
['()']});
}
});
var date = new Date();
$('#div_dob').datetimepicker({
format: 'DD/MM/YYYY',
maxDate : date,
ignoreReadonly: true
});
date=null;
});
Template.Registration.helpers({
location:function(){
$('input[name="txt_address"]').val(Session.get('location'));
}
});
Template.Registration.events({
'click #btn_findlocation':function(event){
alert('Find Location')
event.preventDefault();
function success(position) {
var crd = position.coords;
console.log(`Latitude0 : ${crd.latitude}`);
console.log(`Longitude0: ${crd.longitude}`);
var lat = crd.latitude;
var long = crd.longitude;
reverseGeocode.getLocation(lat, long, function(location)
{
console.log("Address",JSON.stringify(reverseGeocode.getAddrStr()));
Session.set('location', reverseGeocode.getAddrStr());
});
};// end of function success(position)
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};//end of function error(err)
// geolocation options
var options = {
enableHighAccuracy: true,
maximumAge: 0
};// end of var options
navigator.geolocation.getCurrentPosition(success, error,
options);
},
})
}
But I am getting false value for GoogleMaps.loaded() function and the following below error when I click a button to fetch the location.
Can't able to read formatted address of undefined.
Results are inconsistent as sometimes I was able to fetch the location other times not.
Please give any suggestions...

Meteor subscribe is not loading data from the server

I am having difficulties with meteor 1.6. First, I have created a database instance and tried to subscribe in the client. through form, I am able to input the data into my database. But could not retrieve it through the subscribe. can anybody tell me what wrong have I done in my code?
import { Template } from "meteor/templating";
import { Notes } from "../lib/collection";
import { Meteor } from "meteor/meteor";
// import { ReactiveDict } from 'meteor/reactive-dict';
import "./main.html";
/*
Template.body.onCreated(function bodyOnCreated() {
this.state = new ReactiveDict();
Meteor.subscribe("db1");
}); */
Template.Display.helpers({
notes() {
Meteor.subscribe("db1");
return Meteor.call('data');
}
});
Template.body.events({
"click .delete": function() {
Notes.remove(this._id);
},
"submit .formSubmit": function(event) {
event.preventDefault();
let target = event.target;
let name = target.name.value;
Meteor.call("inputs", name);
target.name.value = "";
return false;
},
"click .userDetail": function() {
if (confirm("Delete the user Detail ?")) {
Notes.remove(this._id);
}
}
});
here is the code for publication :
import { Mongo } from 'meteor/mongo';
export const Notes = new Mongo.Collection('notes');
Meteor.methods({
inputs:(name)=> {
if (!Meteor.user()) {
throw Meteor.Error("Logged in");
}
Notes.insert({
name: name,
createdAt: new Date()
});
},
data:()=>{
return Notes.find({});
}
});
Meteor.subscribe("notes"); should be in Template.body.onCreated lifycycle method. you need to write a
publish code seperately and not inside the Meteor.method. see below format,
Meteor.publish('notes', function tasksPublication() {
return Notes.find({});
});
Inside the helper just call the subscribed Collection a below,
Template.Display.helpers({
notes() {
return Notes.find({});
}
});
**NOTE: ** Never use Meteor.call inside the helper method. helpers are reactive and real time.

meteor iron:router Blaze.ReactiveVar calling multiple times

I have a route I call many times. I have to subscribe two collections for having all datas, here's a snapshot:
var one = new Blaze.ReactiveVar(false);
var two = new Blaze.ReactiveVar(false);
this.route('stopIndex', {
path: '/stop/:section/:stop_id',
waitOn: function() {
Meteor.call('getTripIdsForStop', {
stop_id: this.params.stop_id,
from: fromNow(),
to: toMax(),
db: prefix
}, function(err, ids) {
DEBUG && console.log('TRIP_IDS:', ids);
Meteor.subscribe(prefix + '_trips', {
trip_id: {$in: ids}
}, function() {
one.set(true);
});
Meteor.subscribe(prefix + '_stop_times', {
trip_id: {$in: ids}
}, function() {
two.set(true);
});
});
return [
function () { return one.get(); },
function () { return two.get(); }
];
},
The first time I call the route, all goes fine. The second time, the one and two vars are already setted to true so the waitOn doesn't wait and I get a no data message on my template for some seconds, until collections responds. I've tried putting on the first lines of waitOk method:
one.set(false);
two.set(false);
but this makes the waitOn to wait forever. Am I doing something wrong or missing something? Thanks for the help.
I've solved this way:
Router.onStop(function() {
one.set(false);
two.set(false);
});
that invalidates ReactiveVars and will wait. I've also moved all code from waitOn to data. Now the waitOn is like this:
return [
function () { return one.get(); },
function () { return two.get(); }
];

Opening link in javascript widget in new window

I get the following error with this code in the update function below and I don't understand why.
err: [RangeError: Maximum call stack size exceeded]
Does it have something to do with using Meteor.setTimeout()?
if (Meteor.isServer) {
Meteor.clearTimeout(league.nextPickTimeoutId);
var pickTimeoutId = Meteor.setTimeout(function () {
Meteor.call('pickPlayer', leagueId, findTopScoringPlayer(leagueId, nextTeam._id)._id);
}, 30*1000);
Leagues.update(leagueId, {
$set: {
nextPickTill: new Date().getTime() + (league.secondsPerPick * 1000),
nextPickTimeoutId: pickTimeoutId
}
}, function (err) {
if (err) console.log('err:', err);
});
}
The problem was that:
Meteor.setTimeout() returns a handle that can be used by Meteor.clearTimeout. Source
The Meteor.clearTimeout() function confused me that I thought took an id as an argument.

Internal Server Error trying to update server database in Meteor.js

I've been modifying the example meteor app at http://meteor.com/examples/leaderboard. As you can see in the code bellow, I'm trying to update the score of players upon someone hitting the reset button. This updated fine on the client side but in my console I noticed the error "update failed: 500 -- Internal server error". Upon further inspection I saw that indeed, the server side database was not being updated. Any thoughts? (relevant code is in the reset function but I've posted the rest here just in case)
// Set up a collection to contain player information. On the server,
// it is backed by a MongoDB collection named "players."
Players = new Meteor.Collection("players");
var SORT_OPTIONS = {
name: {name: 1, score: -1},
score: {score: -1, name: 1}
}
var NAMES = [ "Ada Lovelace",
"Grace Hopper",
"Marie Curie",
"Carl Friedrich Gauss",
"Nikola Tesla",
"Claude Shannon" ];
function reset(options) {
if (options && options['seed'] === true) {
for (var i = 0; i < NAMES.length; i++) {
Players.insert({ name: NAMES[i], score: Math.floor(Math.random()*10)*5 });
}
}
if (options && options['restart'] === true) {
Players.update( {},
{ $set: { score: Math.floor(Math.random()*10)*5 } },
{multi: true});
}
}
if (Meteor.is_client) {
Template.leaderboard.players = function () {
var sort_by = SORT_OPTIONS[Session.get("sort_by")]
return Players.find({}, {sort: sort_by});
};
Template.leaderboard.selected_name = function () {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
};
Template.player.selected = function () {
return Session.equals("selected_player", this._id) ? "selected" : '';
};
Template.leaderboard.events = {
'click input.inc': function () {
Players.update(Session.get("selected_player"), {$inc: {score: 5}});
},
'click input.sort': function () {
Session.get("sort_by") == "score" ? Session.set("sort_by", "name") : Session.set("sort_by", "score");
},
'click input.reset': function () {
reset({'restart': true});
}
};
Template.player.events = {
'click': function () {
Session.set("selected_player", this._id);
}
};
}
// On server startup, create some players if the database is empty.
if (Meteor.is_server) {
Meteor.startup(function () {
if (Players.find().count() === 0) {
reset({'seed': true});
}
});
}
This also happened to me, but checking the server log, the problem I had was that the $inc modifier requires a number for the argument for the update method, so I made sure it got it with
Number()
Time went by and it now works :) I guess it was some server issue on their demo deploy site.

Resources