Meteor Connection - mongodb

I'm trying to connect my app with mongodb. Adding a post with static array data works fine.
Problem: Nothing shows now up under {{post}}. If I check my DB, there is already data inserted.
Database Insert + Code:
db.calposts.insert({ post: "Hello world!", createdAt: new Date() });
WriteResult({ "nInserted" : 1 })
{{#each calposts}}
{{> posts}}
{{/each}}
<template name="posts">
<div class="panel-post" id="post-draggable">
<span>{{post}}</span>
</div>
</template>
if (Meteor.isClient) {
Template.calendar.helpers({
calposts: function () {
return CalPosts.find({});
}
});
}

Did you publish calpost collection to the client?
If not, in the server folder somewhere you need to use Meteor.publish() and then on the client side, run Meteor.subscribe() to subscribe to the publication.
Check out this page on meteor.com for more info on publishing and subscribing:
https://www.meteor.com/tutorials/blaze/publish-and-subscribe

Related

Meteor access mongo object through client

Many tutorials and documentations later, I still cannot display data from Mongo in the Meteor client.
import { Mongo } from 'meteor/mongo';
export const Skills = new Mongo.Collection('skills')
Template.Skills.helpers({
skills: function() {
return Skills.find();
}
});
skills.html
<template name="Skills">
<h2>My Skills</h2><ul>
{{#each skills}}
{{> SkillItem}}
{{/each}}
</ul>
</template>
entering Skills.find(); in the developer console does not really do anything except give me the following error.
Exception in template helper: ReferenceError: Skills is not defined

How to search collection in meteor with more parameters

I need help with searching the meteor collection with more parameters.
I am using search query and filters to see certain objects from a collection. The problem is that I want client to load whole collection and then reactively change what the user sees, but only changing the subscribe, not calling server again. Thill now search query + one filter is working okay, but only if I call server every time something changes. Now in my code below you can see that I am doing it with if else elements, but that is not a good way. Any suggestion will help. Thank you.
Template.jobs.onCreated( function showOnCreate() {
Meteor.subscribe('Jobs');
this.searchQuery = new ReactiveVar('');
this.remoteQuery = new ReactiveVar(false);
this.typeQuery = new ReactiveVar(false);
});
Template.jobs.helpers({
job: () => {
query = Template.instance().searchQuery.get();
remoteQuery = Template.instance().remoteQuery.get();
typeQuery = Template.instance().typeQuery.get();
let regex = new RegExp( query, 'i' );
// **************************
// the problem starts here
// **************************
if (Router.current().params.slug) {
const companyJobs = Company.findOne({slug: Router.current().params.slug}).jobs;
if ( companyJobs !== undefined) {
return Meteor.subscribe('Jobs', {'_id': { '$in': companyJobs }});
}
return false
} else if (Router.current().params.slug === undefined && remoteQuery === true ) {
return Job.find({ $or: [ { Name: regex }, { Description: regex }, ] , Remote: true, positionType: [],});
} else if (typeQuery = '') {
return Job.find({ $or: [ { Name: regex }, { Description: regex }, ] , positionType: typeQuery, });
},
// -------*****************************
employer: () => {
if (Router.current().params.slug === undefined) {
Meteor.subscribe('Companies');
return 'Poslodavac: ' + Company.findOne({_id: Template.currentData().CompanyId}).Name;
}
return false
},
jobUrl: () => {
Meteor.subscribe('Companies');
companySlug = Company.findOne({_id: Template.currentData().CompanyId}).slug;
return ('/company/' + companySlug + '/job/' );
}
});
Template.jobs.events({
'click .positionType': (event, templateInstance) => {
if (Template.instance().remoteQuery.get().lenght > 1){
Template.instance().typeQuery.set(Template.instance().remoteQuery.get().push(event.target.value));
console.log(Template.instance().remoteQuery.get())
} else {
console.log(Template.instance().remoteQuery.get())
console.log('ggggggg')
Template.instance().typeQuery.set(event.target.value);
}
},
'click #remoteFriendly': (event, templateInstance) => {
Template.instance().remoteQuery.set(!Template.instance().remoteQuery.get());
},
});
Html tempalte with filters:
<template name="jobs" >
<div>
<p>Filteri:</p>
<span>
<input type="checkbox" id="remoteFriendly" name="remote"> <span for="remoteFriendly"> Remote friendly? </span>
</span>
<span>
<p>Tip pozicije:</p>
<input type="checkbox" class="positionType" id="1" value="Programiranje" > <span for="1"> Programiranje </span>
<input type="checkbox" class="positionType" id="2" value="Dizajn" > <span for="2"> Dizajn </span>
<input type="checkbox" class="positionType" id="3" value="Marketing" > <span for="3"> Marketing </span>
<input type="checkbox" class="positionType" id="4" value="Ostalo" > <span for="4"> Ostalo </span>
</span>
</div>
{{#each job}}
<div style="border: 0.1rem solid black; margin: 1cm; padding: 5px; max-width: 420px;" > <!-- OVO JE PRIVREMENI STIL, OBRISATI-->
<p> Posao: {{Name}} <br> Opis: {{Description}}</p>
<p> {{employer}} </p>
<p>Remote friendly?: {{Remote}}</p>
<p>Tip pozicije: {{positionType}}</p>
<p> Saznajte vise OVDE</p>
</div>
{{/each}}
<p id="nesto"></p>
</template>
Welcome to SO!
You seem to be confused between Pub/Sub and Collection.find.
You should first realize that the 2 are different mechanisms, which provide different functionalities.
Pub/Sub indeed sends data from your Server into your Client's Minimongo database. But this data is not displayed yet.
Collection.find is used on your Server against your actual MongoDB, and on your Client against your local Minimongo DB.
Therefore on your client, once you have correctly subscribed to your server publication (typically at app level or template level / in onCreated hook), you can directly call Jobs.find in your helpers (or anywhere else) to get your documents, without having to change the subscription (unless the latter needs new parameters).
There should be nothing wrong with your commented code:
return Job.find({'_id': { '$in': companyJobs }});
In general, avoid any expensive computation in helpers (like Meteor.subscribe), as helpers may be executed many times without you noticing it. Your Meteor.subscribe('Companies') should also go to template level (i.e. in onCreated hook).
Therefore, instead of doing your if / else conditions in your helper, simply do it once at your template level. To account for your need to use a value from another document in another collection, why not just passing directly the company's slug as an argument to your Jobs subscription, and performing the computation Server-side? Or even just subscribing to everything, as your current initial subscription seems to do.
Then your helper will just use Jobs.find, which queries against your Client's local minimongo DB, leaving your Server unbothered.

Simple search function in meteor using EasySearch package

Good Day,
I'm trying to create a simple search function using the easy search package.
In a nutshell I have done the following-
Defined a schema and index on the client as such:
const Patients = new Mongo.Collection('patients');
const PatientsIndex = new EasySearch.Index({
collection: Patients,
fields: ['name'],
engine: new EasySearch.MongoDB()
});
I've entered the following values into the database:
meteor:PRIMARY> db.patients.find()
{ "_id" : ObjectId("57d6a9f71bad26ba07748f9d"), "name" : "Paul" }
Created a template helper on the client side:
Template.searchBox.helpers({
patientsIndex: () => PatientsIndex
});
And lastly I've created a template which should output the results:
<template name="searchBox">
{{> EasySearch.Input index=patientsIndex }}
<ul>
{{#EasySearch.Each index=patientsIndex }}
<li>Name of the patient: {{name}}</li>
{{/EasySearch.Each}}
</ul>
</template>
Now for some reason this just wont work, it renders nothing to the template, I' very new to this and would really appreciate some assistance.
Thanking you.
From your code samples it looks like you're trying to refer to both Patients and PatientsIndex globally. Assuming you have your Patients and PatientsIndex declarations in a shared client/server location (like /lib), then you should remove the const keyword. That will make sure these declarations are available globally, and will allow your Template to use them. Here's a modified version of your code that will work:
/lib/collection.js
Patients = new Mongo.Collection('patients');
PatientsIndex = new EasySearch.Index({
collection: Patients,
fields: ['name'],
engine: new EasySearch.MongoDB()
});
/client/main.html
<body>
{{> searchBox}}
</body>
<template name="searchBox">
{{> EasySearch.Input index=patientsIndex }}
<ul>
{{#EasySearch.Each index=patientsIndex }}
<li>Name of the patient: {{name}}</li>
{{/EasySearch.Each}}
</ul>
</template>
/client/main.js
import { Template } from 'meteor/templating';
import './main.html';
Template.searchBox.helpers({
patientsIndex() {
return PatientsIndex;
}
});

Meteor App - 3 Rows from MongoDB is not displaying on Browser

What wrong with this code?
The 3 rows from mongoDB wont display on browser.
Please help.
My Short Meteor Code
Really cant find what's wrong.
<head>
<title>Things to do.</title>
</head>
<body>
<div class="container">
<header>
<h1>Our List</h1>
</header>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</body>
<template name="task">
<li>{{text}}</li>
</template>
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return Tasks.find({});
}
});
}
db.tasks.find()
2015-08-14T08:27:44.644+0000 trying reconnect to 127.0.0.1:8081 (127.0.0.1) failed
2015-08-14T08:27:44.644+0000 reconnect 127.0.0.1:8081 (127.0.0.1) ok
{ "_id" : ObjectId("55cd9d2456b678da6dcaa972"), "text" : "Hello world!", "createdAt" : ISODate("2015-08-14T07:47:48.586Z") }
{ "_id" : ObjectId("55cd9e2b56b678da6dcaa975"), "text" : "Eat out!", "createdAt" : ISODate("2015-08-14T07:52:11.635Z") }
{ "_id" : ObjectId("55cd9e3e56b678da6dcaa976"), "text" : "Tour around the world.", "createdAt" : ISODate("2015-08-14T07:52:30.944Z") }
There it is, my code in pure text.
A few things that could go wrong:
Your Tasks collection may not be published. Make sure you still have the autopublish package installed in your app, or publish and subscribe to your collection following this tutorial.
You are not using the same Mongodb database as your app's: make sure by printing the app's MONGO_URL.
In your js file:
if (Meteor.isServer) {
console.log(process.env.MONGO_URL);
}

Meteor cannot get data

Im new to meteor, I have a problem I can't get collection from mongodb (i use iron router )
/client/routes.js
Router.route('/page', function(){
this.render('page');
});
/client/foo.js
city = new Mongo.Collection('data');
if (Meteor.isClient) {
Template.foo.helpers({
data: function(){
return city.find();
}
});
}
client/views/foo.html
<template name="foo">
{{#each data}}
{{> all_data}}
{{/each}}
</template>
<template name="all_data">
<li>{{city}}</li>
</template>
in chrome console the command city.find() give me:
L…n.Cursor {collection: LocalCollection, sorter: null, _selectorId:
undefined, matcher: M…o.Matcher, skip: undefined…}
and in mongo console db.data.find() it work fine
i think there a problem to connect to mongodb
The collections need to be defined on both server and client side for autopublish to work -- files in /client are only executed on the client side, so city = new Mongo.Collection('data'); is unknown to the server.
Move the file
/client/foo.js
into the parent directory
/foo.js
And it will likely work