jerrkan
jerrkan

Reputation: 97

Sails.js model, select a specific column from mysql database

I have a problem where GetName is undefined in template file.

The code: http://hastebin.com/wixomerapi.js

But if i write

console.log(results[0].name);

instead of GetName = results[0].name its working fine!

So whats wrong here? :/

Upvotes: 1

Views: 769

Answers (2)

jemiloii
jemiloii

Reputation: 25719

Even better solution is to use the options parameter and set select.

Model.find({field: 'value'}, {select: ['id', 'name']})
  .paginate({page: 1}, {limit: 10)
  .exec(function(err, results) {
    if(err) {
      res.badRequest('reason');
    }
    res.json(results);
});

Upvotes: 1

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

Try this,

ViewGame: function (req, res) {
    var GetName;
    Games.findBySlug(req.params.tournamentName).exec(function(err, results) { 
    GetName = results[0].name;
    res.view('game/view', {
        name : GetName,
    });
 });        
},

You have to learn how Javascript callbacks work.

In your code function execution happens in following order after the ViewGame function is called:

  1. Games.findBySlug(req.params.tournamentName).exec( ) function is called scheduling the following callback function to be called later.

    function(err, results) { 
         GetName = results[0].name;
    });
    
  2. following function is called.

    res.view('game/view', {
        name : GetName,
    });
    
  3. following function (scheduled at 1st step) is called.

    function(err, results) { 
        GetName = results[0].name;
    });
    

as a result of this GetName is not assigned (assignment happens in 3rd step) when it is set in "res.view" in 2nd step. But when you use "console.log" it simply prints the value of "results[0].name" in 3rd step.

Upvotes: 0

Related Questions