【问题标题】:Insert more then 1 object into MongoDB error将超过 1 个对象插入 MongoDB 错误
【发布时间】:2019-02-25 20:20:08
【问题描述】:
// 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 是一个对象数组;

 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 个以上的对象保存到 db 中? 交易

【问题讨论】:

标签: javascript ajax reactjs mongodb


【解决方案1】:

问题是您只执行一个保存操作,然后将响应发送到客户端。使用 Promise 池并使用 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 语句中返回,else 不是必需的。

【讨论】:

  • 我们只在循环内执行 arr.save() 并在循环外返回 res.json({ success: 'success' }) 怎么样?这有效吗?
  • 不,因为 arr.save() 是异步操作。您必须使用 async/await 才能做到这一点。
猜你喜欢
  • 2017-10-21
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多