首页 > 解决方案 > 无法将两个 api 调用链接到 mongo 数据库

问题描述

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

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

路由.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 });
    });
});

问候

标签: javascriptnode.jsmongodbmongoose

解决方案


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

更快的人会返回并回答(res.send)并关闭连接。当第二次更新完成时 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 两次。

祝你好运


推荐阅读