0

I am trying to save a json object that is sent by a client, in the database
The application can handle requests just fine, but i am stuck when it comes to saving the request data in the database, i am using sequelize. Here are my models:

Schedule Model

module.exports = (sequelize, DataTypes) => {
  const Schedules = sequelize.define('Schedules', {
    name: DataTypes.STRING,
    delay: DataTypes.INTEGER,
    criteria: DataTypes.STRING
  }, {})
  Schedules.associate = (models) => {
    Schedules.hasMany(models.Commands)
  }
  return Schedules
}

and the commands model

module.exports = (sequelize, DataTypes) => {
    const Commands = sequelize.define('Commands', {
        command: DataTypes.STRING,
        index: DataTypes.INTEGER
    },{})
    Commands.associate = (models) => {
        Commands.belongsTo(models.Schedules)
    }
    return Commands
}

Finally here is the request json object that is recieved

{
    "name": "Do Something",
    "commands": [
        "step one",
        "step two",
        "step three"
    ]
}

Also i need to make sure when a schedule is queried, it shall return the commands[] array in that order. My Question is, How can i do so in sequelize, Any help is appreciated. Thanks

1 Answers1

0

Fist you need to import those sequelize models in file where you want to work with them:

const schedulesModel = require(path to your defined model Schedules)
const commands = require(path to your defined model Commands )

let's say you have a endpoint for POST operation:

exports.createSchedulesAndCommands = **async** (req, res, next) => {

you need to create a "parent" object first:

const schedule = await schedulesModel.create({name: parse.body.name});

then to iterate to every element of array and based on scheduled object (just created) sequelize present "magic" methods, that have sintax createAssociatedModelName.

await Promise.all(
      parse.body.commands.map(async command => {
        await schedule.createCommands({command: command});
      })
    );

You may want to consider checking documentation of sequelize realated for associations: https://sequelize.org/master/manual/assocs.html Hope this helps.

vujadin
  • 66
  • 2