无法将两个api调用链接到mongo数据库

时间:2019-02-09 20:33:03

标签: javascript node.js mongodb mongoose

我需要从Mongo文档中更改: 1.数组内所有对象的一个​​属性 2.数组内一个对象的一个​​属性。

我查看了猫鼬文档,它说exec()使您的查询成为完整的promise。好吧,我不太了解,然后我尝试将它们链接起来,但不确定是否做得很好。

route.js

router.patch("/internado/:id", (req, res, next) => {
  const id = req.params.id;
  const updateOps = {};
  for (let prop in req.body) {
    updateOps[prop] = req.body[prop];
  }

  User.update(
    { _id: id },
    // this changes every element from object inside array
    // already tested the command in postman
    { $set: { "datosAcademicos.internados.$[].activo": false } }
  )
  .exec()
  .then(result => {
      console.log(result);
      res.status(200).json(result);
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({ error: err });
    });

  User.update(
    { _id: id },
    // pushs the new element to array. Also tested by itself on postman
    { $push: { "datosAcademicos.internados": updateOps } }
  )
    .exec()
    .then(result => {
      console.log(result);
      res.status(200).json(result);
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({ error: err });
    });
});

致谢

1 个答案:

答案 0 :(得分:1)

首先,两个更新都将在某个时间结束,

,更快的将返回并应答(重新发送)并关闭连接。 当第二个更新完成时,res.send已关闭,并且将引发异常。

您不能保证哪一个先完成,如果顺序对您而言很重要,那么您应该真正将其链接起来,而不仅仅是一个接一个地写它们。

如果这对您来说并不重要,或者您只关心其中一个结果, 在您的代码中反映出来。

因此,如果您要链接,那么(一个接一个):

// lets execute the first update
User.update(
  { _id: id },
  { $set: { "datosAcademicos.internados.$[].activo": false } }
).exec()
// now we wait for it to finish
.then(res => {
   // do something with the first update ?
   // possibly res.send if you did like

   // now execute the other Update
   return User.update(
      { _id: id },
      { $push: { "datosAcademicos.internados": updateOps } }
   ).exec()
})
.then(res2 => {
   // possible res.send / other logging
   res.send('done all updates');
})
.catch(err => {
   console.log(err);
   res.status(500).json({ error: err });
});

如果要一起执行它们而不必等待第一个:

Promise.all([
   User.update(
     { _id: id },
     { $set: { "datosAcademicos.internados.$[].activo": false } }
   ).exec(),
   User.update(
      { _id: id },
      { $push: { "datosAcademicos.internados": updateOps } }
   ).exec()
])
// wait for both of them to finish , order not guaranteed 
.then(result => {
   // result[0] - result for first update
   // result[1] - result for second update ..
   res.send(result);
})
.catch(err => {
   console.log(err);
   res.status(500).json({ error: err });
});

如果您只关心一个结果,但仍想执行两个更新,则只需将其反映在代码中,这样就不会调用res.send两次。

祝你好运