Meteor.publish() - how to get documents by free text - meteor

I trying to get documents by free text.
This part, that getting data by field works OK and returns data:
Meteor.publish("messages", function(){
return Messages.find({ discussion_id: "discus_id_87" });
});
This one doesn't work:
Meteor.publish("messages", function(){
return Messages.find({ $text: { $search: "Some text" } });
});
Returns an ERROR:
Error: Exception while polling query {"collectionName":"messages","selector":{"$text":{"$search":"Some text"}},"options":{"transform":null}}: Unable to execute query: error processing query: ns=meteor.messages limit=0 skip=0
This is an example from mongoDB $text
db.articles.find( { $text: { $search: "bake coffee -cake" } } )
What I'm doing wrong?
How to get documents by free text?
Thanks

Make sure your mongo database is version 2.6. This is a relatively new MongoDB feature.
Also, you are required to create an index:
Meteor.startup(function (){
Messages._ensureIndex({"$**": "text"}, {"name": "searchIndex"});
});
More info here: http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/

Related

Ionic2 - SQLite executing SQL

I'm creating app with using SQLite. I have some problems with using SQLite.
I have page with variable for managing database.
public sqlite_object: any;
In the constructor i'm opening/creating if not exists database, and saving db object to variable.
constructor(...){
let name = 'db_name';
this.openDatabase(name);
}
openDatabase(name){
let db = new SQLite();
db.create({ name: name, location: 'default' })
.then( (db_obj: SQLiteObject) => {
this.sqlite_object = db_obj
}, (error) => {
alert('error');
}
}
So, in the constructor i'm opening db, and saving it for future.
On of buttons calling that function:
testSQL(sql_queries){
this.sqlite_object.transaction( function(tx){
Object.keys(sql_queries)
.sort()
.forEach( function(v,i){
tx.executeSql(sql_queries[v],
null,
function (transaction, result){
alert('executing sql');
},
function (transaction, error){
alert('error');
});
});
}, function (error){
alert('error2');
}, function (){
alert('success');
}
}
My sql_queries have about ~30 queries (correct and incorrect).
When i put alert into forEach(), it will be executed everytime (same times as sql_queries length).
When executeSql(...) getting incorrect query, alert about error is showing, but i never seen alert 'executing sql' - is sth wrong here? (i don't know if my queries executing correctly)
Also i have one more question. How can i get list of tables from my database?
your "executing sql.." is inside a success callback function. it will be executed after the entire for each() query is successful (not after each loop). So as you said it's showing error. So, It will not execute the successcallback function. else it will execute the errorcallback function. this is beacause your entire query is not successful. I hope you get the point

How to make appear collection in the email?

I’m making an app, where users can leave their comments. All reviews are going to Mongo collection. Every week cron-job takes records from collection and sent them by e-mail.
I used the code below and I got not what was expecting. Email text was just: [Object, object].
Can anyone can explain me how should I properly write this line:
var myMessages = FeedbacksList.find({}).toString();
to get my app work corectly?
ALL CODE:
// Methods
Meteor.methods({
sendEmail: function (to, from, subject, text) {
Email.send({
to: to,
from: from,
subject: subject,
html: text
});
}
});
Meteor.methods({
'feedbacks.insert'(emoji, feed, timeSet) {
FeedbacksList.insert({
feedback: emoji,
knowFrom: feed,
createdAt: timeSet
});
}
});
var myMessages = FeedbacksList.find({}).toString();
// Cron Job for weekly email sending
SyncedCron.add({
name: 'Jura Ataskaitos',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('at 9:00 am on Mon');
},
job: function() {
const sendM = Meteor.call('sendEmail', 'karolis.arbaciauskas#gmail.com', 'karolis#pretendentas.lt', 'test', myMessages);
return sendM;
}
});
// Start Cron
SyncedCron.start();
Note that the following returns a cursor
FeedbacksList.find({})
If you want to get all the records returns by this, then you need to fetch them:
var messages = FeedbacksList.find({}).fetch()
Or you can iterate over them:
FeedbacksList.find({}).fetch().foreach(function(message) {
console.log(message);
});

Data from db undefined at first, then changes to actual data

I am doing a find on a collection of nodes and am then storing the info in a variable.
I am then console.logging this data to see the contents of it. The thing is, my data stays an empty array for a split second and then a new console.log is done with an array of data. See my code below:
Template.temperature.helpers({
node() {
let node = Nodes.find({_id:Session.get('selectedNode')});
console.log(node);
return '';
}
});
My console output:
1: []
2: [Object]
What could be the reason for this?
In your router, subscribe within waitOn:
Router.route('/home', {
waitOn: function() {
return [
Meteor.subscribe('nodes'),
];
},
action: function() {
if (this.ready()) {
this.render();
}
},
});
This will ensure that the route will wait until the subscription is completed before executing the route. It uses the meteor loading hook, so the wait will utilize whatever loading screen or animation you ahve setup.

Iron Router waitOn not working when setting data on a route in Meteor 1.0.2

I'm defining a route that will show an appointment for a patient. I would like the template to show both the patient information and the appointment information.
I have this published:
Meteor.publish('userAppointment', function(appointmentId){
check(appointmentId, String);
var userId = Appointments.findOne(appointmentId).patientId;
return [
Appointments.find({_id: appointmentId}),
Meteor.users.find({_id: userId}, {fields: {profile: true, emails: true}})
];
});
Unfortunately Iron Router doesn't seem to be successfully waiting on the data subscription to complete before it tries to set the data context.
Note where I put debugger:
Router.route('/admin/appointment/:id', {
name: 'AppointmentShow',
waitOn: function(){
return [
Meteor.subscribe("userAppointment", this.params.id)
]
},
data: function(){
var appointmentId = this.params.id;
debugger
var patientId = Appointments.findOne(appointmentId).patientId;
return {
appointment: Appointments.findOne(appointmentId),
patient: Meteor.users.findOne(patientId)
}
}
});
At the time when debugger stops the code, when I do Meteor.users.find().fetch() and Appointments.find().fetch() in the console only the currently logged-in user (me) is available and there are no appointments available.
I expect to see two users (me and the patient) and one appointment available because that's the data that should be available after the waitOn has finished subscribing.
Am I missing something here?
EDIT----- Still doesn't make sense to me ------
When I change my route to this:
Router.route('/admin/appointment/:id', {
name: 'AppointmentShow',
waitOn: function(){
return [
Meteor.subscribe("userAppointment", this.params.id)
]
},
data: function(){
var appointmentId = this.params.id;
return {
appointment: Appointments.findOne(appointmentId),
// patient: Meteor.users.findOne(Appointments.findOne(appointmentId).patientId)
}
}
});
Appointments.findOne(appointmentId) returns an object:
{
_id: "23efref34qr2",
reason: "coughing",
patientId: "785g45g4f"
}
When my data function only returns
appointment: Appointments.findOne(appointmentId)
it works. But if I have it also return
patient: Meteor.users.findOne(Appointments.findOne(appointmentId).patientId)
I get an error message (can't read property 'patientId' of undefined.) Huh? It was just defined on the line above!
To clarify, I think you should be allowing your data function to run (and rerun when collections are populated), but be careful to make sure your function doesn't throw an error when it runs before data is available. This is a general Meteor pattern.
data: function(){
var appointmentId = this.params.id,
appointment = Appointments.findOne(appointmentId);
return { appointment: appointment,
patient: Meteor.users.findOne(appointment ? appointment.patientId : null) }
}
Sorry about the formatting, I'm doing this from an awful phone...
The problem seems to be that it runs the data function() before running the waitOn, and is therefore timing dependent. I have seen the same problem, and also had to check if the data was actually there.

Using JayData to fetch the data from sql server into websql browser

I am trying to add the entity which is related to another entity
onlinedb.DemoShifts.filter("it.EmployeeID ==="+empID).toArray(function (DemoShift) {
DemoShift.forEach(function (demoShift) {
offlinedb.DemoShifts.add(demoShift);
alert("Add DemoShift");
onlinedb.Sites.filter("it.SiteID==="+demoShift.SiteID).toArray(function(Sitess){
Sitess.forEach(function(site){
onlinedb.SiteChains.filter("it.ChainID==="+site.ChainID).toArray(function (chains) {
offlinedb.attach(chains[0]);
alert("Add SiteChain");
});
offlinedb.add(site);
var res = offlinedb.saveChanges();
res.done(function () { alert("Success"); });
res.fail(function (ex) { alert("Success"); });
});
});
});
});
I am getting this error "Context already contains the entity"
What is exactly wrong I am doing Can you tell me is there any way I can check if the entity already exists or something?
The library throws this error if the entity is attached more than one. What happens if you comment the following line?
offlinedb.attach(chains[0]);

Resources