0
votes

So, I'm creating a small application using SailsJS. My database is MySQL. When I'm testing, first I create a "market" record, then a "stock" record linked to "market" and in another moment, I retrieve this stock record.

I have the following models:

Stock model:

module.exports = {

  attributes: {
    intern_id: {
      type: 'string'
    },
    tick: {
      type: 'string'
    },
    market: {
      model: 'market'
    }
  }
};

Market model:

module.exports = {
  attributes: {
    tick: {
      type: 'string'
    },
    name: {
      type: 'string'
    },
    description: {
      type: 'string'
    },
    stocks: {
      collection: 'stock',
      via: 'market'
    },
  }
}

Then, first I create a "market" and use the object returned to associate with my "stock" object:

Create and get my market record:

Market.create({tick: 'BVMF', name: 'Bovespa', description: 'Bolsa de Valores'}).exec(function(err, market) {
    if(err) done(err);
});

var market = Market.findOne({tick: 'BVMF'}).then(function(results){return results;});

Create my stock record:

Stock.create({intern_id: '1234', tick: 'VALE5', description: 'Vale SA', market: market}).exec(function(err, stock) {
   if(err) done(err);
});

And then, when I try to get back this stock, the market object is not retrieved, even if I call populate('market'):

Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {    
   console.log(record);
});
1

1 Answers

2
votes

Not too much information, but I guess.

Instead:

Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {    
   console.log(marketObj);
});

Should be:

Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {    
   console.log(record);
});


Second answer:

You forgot about asynchronous. You should do this like that:

Market.create({tick: 'BVMF', name: 'Bovespa', description: 'Bolsa de Valores'}).exec(function(err, market) {
    if(err){
        done(err);
    } else {
        Stock.create({intern_id: '1234', tick: 'VALE5', description: 'Vale SA', market: market.id}).exec(function(err, stock) {
            if(err){
                done(err);
            } else {
                Stock.findOne({tick: stock.tick}).populate('market').exec(function(err, record) {    
                    console.log(record); // and there is your "Stock" with populated "market"
                });
            }
        });
    }
});