Search code examples
javascriptnode.jssails.jsmodel-associations

Why doesn't .add() insert value in the column?


I'm trying sails.js association using one way reference (according to sails.js in action book). Now, the value of owner is successfully inserted in owner column, but value in cars column is not inserted.

When I tried console.log(foundDriver) and console.dir(foundDriver), it showed following things:

{ id: 1, Name: 'asdf' }

{ cars: [Getter/Setter], id: 1, Name: 'asdf' }

My tables (1: driver, 2: car):

enter image description here enter image description here

CODE:

Car.js

module.exports = {
  connection: 'mysqlAdapter',
  tableName: 'car',
  attributes: {
    id: {
      type: 'integer',
      primaryKey: true
    },
    Name: {
      type: 'string'
    },
    Brand: {
      type: 'string'
    },
    Model: {
      type: 'string'
    },
    owner: {
      model: 'driver'
    }
  }
};

Driver.js

 module.exports = {
 connection: 'mysqlAdapter',
 tableName: 'driver',
 attributes: {
   id: {
     type: 'integer',
     primaryKey: true
   },
   Name: {
     type: 'string'
   },
   cars: {
     collection: 'car'
   }
 }
};

CarController.js

    module.exports = {
    createCars: function (req, res) {
        Driver.findOne({
            id: 1
        }).exec(function (err, foundDriver) {
            if (err) {
                console.log("Err1" + foundDriver);
            }
            if (!foundDriver) {
                console.log("Err2");
            }
            Car.create({
                Name: "car1",
                Brand: "brnd",
                Model: "mdl",
                owner: foundDriver.id
            }).exec(function (err, createdCar) {
                if (err) {
                    console.log("Err3");
                }
                foundDriver.cars.add(createdCar.id);
                    foundDriver.save(function (err) {
                     if (err) {
                         console.log(foundDriver);

                      }
                          return res.json({id: 100});
                    });
            });
        });
    }
    };

Solution

  • It will not be inserted because its 'virtual' data. When you want to get those data you need to join those 2 tables.

    Driver.find({
    
    }).populate('cars').exec(function(error, drivers){
    
    });
    

    Query sent to database will look more like this

    select * from driver inner join car where driver.id = car.owner