将更多然后1个对象插入MongoDB错误

时间:2019-02-25 20:20:08

标签: javascript ajax reactjs mongodb

npm

item是一个对象数组;

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

有没有一种方法可以在1次调用中将1个以上的对象保存到db中? tx

1 个答案:

答案 0 :(得分:0)

问题是您只执行一个保存操作,然后将响应发送到客户端。使用承诺池并使用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并非必需。