0
// Load User Model
const User = require('../../models/User');
const Item = require('../../models/Item');

router
 .post('/login/:id', passport.authenticate('jwt', {session: false}), (req, res) => {

  const { item } = req.body;

item is an array of objects;

 User.findOne({ _id: req.params.id })
  .then(user => {
    console.log(user);

it returns the right user

    if (user._id.toString() !== req.user._id.toString()) {
      // Check for owner
      return res.status(401).json({ notAuthorized: 'User not authorized' });
    } else {
      for (let i = 0; i < item.length; i++) {
        const arr = new Item ({
          user: req.user._id,
          name: item[i].name,
          quantity: item[i].quantity,
        })
        arr.save().then(() => res.json({ success: 'success' }))
      }
    }
  })
  .catch(err => res.status(404).json({ noUserFound: 'User not found' }))

is save to db but i have an error

   Cannot set headers after they are sent to the client

is there a way you can save more then 1 object into db in 1 call? tx

TextError
  • 339
  • 3
  • 5
  • 11
  • Possible duplicate of [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Naing Lin Aung Feb 25 '19 at 20:38

1 Answers1

0

The problem is that you're only executing one save operation and then sending the response to the client. Use a pool of promises and fetch them with Promise.all:

User.findOne({ _id: req.params.id })
    .then(user => {
        console.log(user);
        if (user._id.toString() !== req.user._id.toString()) {
            // Check for owner
            return res.status(401).json({ notAuthorized: 'User not authorized' });
        }
        // Here we create an array of promises. These will be resolved later on
        const promises = []
        for (let i = 0; i < item.length; i++) {
            const arr = new Item({
                user: req.user._id,
                name: item[i].name,
                quantity: item[i].quantity,
            })
            // Here we add a single save promise into the array.
            promises.push(arr.save())
        }
        // Here we perform all the Promises concurrently and then send the response to the client.
        return Promise.all(promises)
    })
    .then(() => res.json({ success: 'success' }))
    .catch(err => res.status(404).json({ noUserFound: 'User not found' }))

Bonus, since we return inside the if statement, the else is not neccessary.