javascriptsails.jssails-mongosails.io.js

Sailsjs create objects - nested creations


I have a controller which accepts an API call /task/:id/start. My controller method needs to check if Task with at id is valid and if that's valid then I need to create 2 other model instances. I need to create TaskSet and then TaskSetEvents.

TaskSet requires task to be created and TaskSetEvents requires TaskSet to be created. Here is how I'm planning on creating these events. I'm not sure if there is a better way of creating these objects.

TaskSet.create({ task: task}).exec(function(err, taskSet) {
    TaskSetEvent.create({ taskSet: taskSet, eventType: 'start'}).exec(function (err, taskSetEvent) {
        console.log("Everything created ok");
    });
});

Solution

  • This should just work:

    TaskSetEvent.create({
        eventType: 'start',
        taskSet: {
          task: myTask
        }
      })
      .then(function (taskSetEvent) {
        console.log('should be done here');
      });
    

    If you're doing this through a controller endpoint, you shouldn't have to write any code. Just POST your nested object.