Insert in bulk using Sequelize with Node and Express

十年热恋 提交于 2021-02-08 08:20:36

问题


Looking for a way to insert activities to the database in bulk using Sequelize Model.bulkCreate.

Not sure how to bring the activities from the view to the route function in order to insert them using bulkCreate. Right now I only insert one activity.

View:

<form action="/create" method="POST">
  <div class="form-group">
    <label>Plan Name</label>
    <input type="text" name="plan_name" placeholder="Plan Name">
  </div>
  <div class="form-group">
    <label>Description</label>
    <input type="text" name="description" placeholder="Description">
  </div>
  <div class="form-group">
    <label>Activity</label>
    <input type="text" name="activity_name" placeholder="Activity">
    <label>Comment</label>
    <input type="text" name="comment" placeholder="Comment">
    <input type="button" id="add" class="btn btn-success" value="Add">
  </div>
  <div class="form-group" id="new">
  </div>
    <input type="hidden" name="_csrf" value="{{csrfToken}}">
    <input type="submit" class="btn btn-success" value="Submit">
</form>
<script type="text/javascript">
  $('#add').click(function() {
    let activity = $('<div class="form-group"><label>Activity</label><input type="text" name="activity_name" placeholder="Activity"><label>Comment</label><input type="text" name="comment" placeholder="Comment"></div>');
    $('#new').append(activity);
  });
</script>

Route:

  app.post('/create', (req, res) => {
    const user_id = req.user.id;
    const data = {
      plan_name: req.body.plan_name,
      description: req.body.description,
      userId: user_id
    };
    PlanModel.Plan.create(data).then(plan => {
      const activity = {
        activity_name: req.body.activity_name,
        comment: req.body.comment,
        plans_id: plan.id
      };
      ActivityModel.Activity.create(activity);
      res.redirect('/');
    });
  });

回答1:


1) Make fields to have names like an array

<div class="activities">

  <div class="form-group">
    <label>Activity</label>
    <input type="text" name="activities[0][name]" placeholder="Activity">
    <label>Comment</label>
    <input type="text" name="activities[0][comment]" placeholder="Comment">
  </div>

  <div class="form-group">
    <label>Activity</label>
    <input type="text" name="activities[1][name]" placeholder="Activity">
    <label>Comment</label>
    <input type="text" name="activities[1][comment]" placeholder="Comment">
  </div>

</div>

<div class="form-group>
  <input type="button" id="add" class="btn btn-success" value="Add">
</div>

2) At server-side just take that req.body.activities and generate array of objects and call bulkCreate

app.post('/create', async (req, res) => {
  try {
    const data = {
      plan_name: req.body.plan_name,
      description: req.body.description,
      userId: req.user.id
    };
    const plan = await PlanModel.Plan.create(data);


    if (req.body.activities && Array.isArray(req.body.activities)) {
      const activities = req.body.activities.map(
        activity => {
          return {
            activity_name: activity.name,
            comment: activity.comment,
            plans_id: plan.id
          }
        });
      await ActivityModel.Activity.bulkCreate(activities);
    }

    res.redirect('/');
  }
  catch(error) {
    res.status(500).send(error);
  }
});

3) Since body parser for urlencoded mode has extended option that parses deeply all of the fields. You've to enable it.
MAKE SURE that bodyParser middleware attached with extended: true :

 const bodyParser = require('body-parser');
 app.use(bodyParser.urlencoded({extended: true}));


来源:https://stackoverflow.com/questions/50358641/insert-in-bulk-using-sequelize-with-node-and-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!