快递请求多对多

时间:2018-03-28 15:38:47

标签: node.js rest express post sequelize.js

我有两个表:用户和材料有m:m的关系。交集实体是journalMaterials。我正在尝试发送POST请求以插入journalMaterials。此外,该表有2个属性:recycledQuantity和recycleDate。我尝试了一些东西,但如果我插入一个不存在的materialId,它就不会给我“找不到”。

 app.post('/users/:uid/materials/:mid', (req, res, next) => {
  User.findById(req.params.uid)
    .then((user) => {
      if (user){
        let journalMaterial = req.body
        journalMaterial.userId = user.id
        Material.findById(req.params.mid)
         .then((material) => {
           if (material){
            journalMaterial.materialId = material.id
            return JournalMaterial.create(journalMaterial)
           }
           else{
        res.status(404).send('not found')
      }
         })}
      else{
        res.status(404).send('not found')
      }
    })
    .then(() => {
      if (!res.headers){
        res.status(201).json('created')
      }
    })
    .catch((err) => next(err))
})

2 个答案:

答案 0 :(得分:1)

我已经解决了。这是正确的代码。

app.post('/users/:uid/materials/:mid', (req, res, next) => {
      const { uid, mid } = req.params;
      Promise.all([
        User.findById(uid),
        Material.findById(mid)
      ])
        .then(([user, material]) => {
          if (user && material) {
            let journalMaterial  = req.body
            journalMaterial.userId = user.id
            journalMaterial.materialId = material.id
            res.status(201).json('created')
            return JournalMaterial.create(journalMaterial)
          }
          res.status(404).send('not found')
        })
        .catch(err => next(err));
    })

答案 1 :(得分:0)

略微重写这个以使其更具可读性。删除了你的嵌套承诺电话......(当他们试图摆脱回调地狱时,不要潜入承诺地狱......)

app.post('/users/:uid/materials/:mid', (req, res, next) => {
  const { journalMaterial } = req.body;
  const { uid, mid } = req.params;
  Promise.all([
    User.findById(uid),
    Material.findById(mid)
  ])
    .then(([user, material]) => {
      if (user && material) {
        journalMaterial.userId = user.id;
        journalMaterial.materialId = material.id;
        return JournalMaterial.create(journalMaterial);
      }
      res.status(404).send('not found');
    })
    .then(() => {
      if (!res.headers) {
        res.status(201).json('created');
      }
    })
    .catch(err => next(err));
});

您对if(user)的检查目前已通过。似乎如果发生了什么,你总是得到一个对象。许多数据库通常不会返回nullfalse值,而是返回包含大量元数据的对象。在该对象中通常是您请求的数据(即user.data.id,但可能是user.data为NULL)。你能核实Users的确切内容是什么吗?它正在评估真实性,因此它必须有一些东西。

相关问题