MySQL query synchronously

I am using following MySQL package for database interaction in Meteor 2.7:

I am stuck at a point where I need to fetch data Synchronously.

I am running 2 separate queries where 2nd query’s result is dependent on first query’s result.

Here is my example script:

(This usersClass provides data to restivus api endpoint)

Meteor.startup(function () { 

    usersClass = {
    	getUsers: function (age){
    		var query = `SELECT * FROM users WHERE age = ${age}`;
    		connection.query(query, function (error, results, fields) {
    		  if (error) throw error;
    		return results;
    	getHobbies: function (userId){
    		var query = `SELECT * FROM hobbies WHERE userId = ${userId}`;
    		connection.query(query, function (error, results, fields) {
    		  if (error) throw error;
    		return results;
    	getStatistics: function (params){
    		var users = this.getUsers(params.age); // Some processing on users list data fetched from this.getUsers
    		var hobbies = this.getHobbies(params.userId); // Some processing on hobbies after fetching users data

As you can see hobbies data is dependent on the response result of users response.

I need all these queries to be synchronous where each query in sequence should wait for its process to be completed and then it should proceed for another query’s response.

Any help is appreciated. Thanks

In a previous project I used the mysql2 package

It supports a promise wrapper mysql2 - npm

MySQL2 also support Promise API. Which works very well with ES7 async await.

async function main() {
  // get the client
  const mysql = require('mysql2/promise');
  // create the connection
  const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
  // query database
  const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);

If you use meteor/promise

import { Promise } from 'meteor/promise'

You can then do a synchronous call like this:

const [data] = Promise.await(mysql.query(sql, params))

I actually created an ORM for mysql using the above approach, which allows you to write CRUD calls to mysql tables using the same syntax as if you were using Mongodb in Meteor. This has the advantage of being easier to write the code, and you could switch databases relatively easily.

I can share that code with you if you like

Actually I am bit confused with restivus, that how will restivus interact with async function

Restivus give you an easy way to provide endpoint for your mongo collections with little code.
The Restivus api functions can contain Meteor code, there should be no problem in using the above approach to do what you want.

1 Like

Try using a publication and subscribe to it.

var liveDb = new LiveMysql(Meteor.settings.mysql);

Meteor.publish('allPlayers', function(){
    `SELECT * FROM players ORDER BY score DESC`,
    [ { table: 'players' } ]

Actually I don’t need reactive data from MySQL. I use Restivus plugin for throwing data on specific endpoints. That’s where I need to provide asynchronous data to a specific endpoint

Use a method then bud, just call your query from the client and you’ll be good to go

Any example comes to mind? since I am unable to find it in the documentation

  1. Click the link I sent
  2. Scroll down the page
import SimpleSchema from 'simpl-schema';

  'todos.updateText'({ todoId, newText }) {
    new SimpleSchema({
      todoId: { type: String },
      newText: { type: String }
    }).validate({ todoId, newText });

    const todo = Todos.findOne(todoId);

    if (!todo.editableBy(this.userId)) {
      throw new Meteor.Error('todos.updateText.unauthorized',
        'Cannot edit todos in a private list that is not yours');

    Todos.update(todoId, {
      $set: { text: newText }

When I started coding you got banned from forums for not reading the manual. Times have changed. Now I will be shadow banned or temporarily muted for telling you to read the manual. Millennials have it really different.