Search code examples
mongodbsails.jssails-mongo

Change more than one table via sails controller


I want my sails controller to perform these steps:

-add word to Word table

-take the created word's ID and add it alongside with lesson's ID to a different table

module.exports = {
   add: function(req,res){
        var eng=req.param('english'), 
            pol=req.param('polish'),
            lessonID=req.param('lessonID');
        var wordID=this.create(eng,pol,lessonID);
        console.log(wordID);
    },

   create: function(eng,pol,lessonID){
           sails.models.word.create({
               english:eng,
               polish:pol})
           .exec(function (word){
            return word.id

   });
}
};  

I'm not sure how to return the wordID to the add function. Right now wordID is 'undefined'. I've tried changing the declaration of create to:

create(req,res)

and then return

res.json(200, { id: word.id });

but it didn't change anything. What is the proper way to deal with functions of this type?


Solution

  • You have misunderstood the asynchronous nature of javascript.

    var wordID=this.create(eng,pol,lessonID);
    console.log(wordID);
    

    Console.log will be executed immediately after the previous line.The database operation wont be complete by that time. You need to change the create method to accept a callback that needs to be executed once db operation is done.

    add: function(req,res){
            var eng=req.param('english'), 
                pol=req.param('polish'),
                lessonID=req.param('lessonID');
            this.create(eng,pol,lessonID, (wordID) => { 
                console.log(wordID);
                return res.json({wordID});
            });
        },
    
       create: function(eng,pol,lessonID, callback){
               sails.models.word.create({
                   english:eng,
                   polish:pol})
               .exec(function (word){
                return callback(word.id);
    
       });
    }