Вставить более 1 объекта в ошибку MongoDB - PullRequest
0 голосов
/ 25 февраля 2019
// 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;

элемент представляет собой массив объектов;

 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' });
    } 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' }))

сохранен в БД, но у меня есть ошибка

   Cannot set headers after they are sent to the client

Есть ли способ сохранить более 1 объекта в БД за 1 вызов?ТХ

1 Ответ

0 голосов
/ 25 февраля 2019

Проблема в том, что вы выполняете только одну операцию сохранения, а затем отправляете ответ клиенту.Используйте пул обещаний и извлекайте их с бонусом 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' }))

, так как мы возвращаемся в операторе if, остальное не является необходимым.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...