简体   繁体   中英

How to save the array field in database

here producerId value [3,5], and i want to save in database like { "id" :"1","userId" :"3"},{"id":"2","userId":"5"}

  const Ids =  _.map(req.body.producerId, (user) => ({
    const projectList =  await ProjectTeam.create({
      userId: user,
      });
      return res.json({
        success: true,
        message: 'added successfully! ',
      });

multiple insert at the database with a loop it's a bad idea because it's multiple request to database.

i suggest you to organise your objects and insert all in one rquest like :

var ids = req.body.producerId;
var users = [];
for(let i = 0; i<ids.length ;i++){
    users.push({
    userId: ids[i],
  })
}

ProjectTeam.bulkCreate([
  users
]).then(()=>{
  return res.json({
    success: true,
    message: 'added successfully! ',
  });
});

for you problems check if req.body.producerId it's not empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM