最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法链两个API调用到蒙戈数据库

运维笔记admin8浏览0评论

无法链两个API调用到蒙戈数据库

无法链两个API调用到蒙戈数据库

我需要从蒙戈文档改变:1.一种从所有对象属性的数组内2.一从一个对象属性的阵列内。

我看着猫鼬文档和它说的exec(),使您的查询的完整promise。嗯,我不太明白,那么我想他们链接,但我不知道如果我做就OK了。

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 });
    });
});

问候

回答如下:

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

而较快的将返回并回答(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两次。

祝好运

发布评论

评论列表(0)

  1. 暂无评论