【问题标题】:mongoosejs return a model.find with an altered objectmongoosejs 返回一个带有更改对象的 model.find
【发布时间】:2019-07-10 13:42:26
【问题描述】:

我在查询我的 mongoose 模型并将更改的对象传递给下一个 Promise 链时遇到问题。

查询确实会传递给下一个 .then,但没有我新分配的 spaceTempName。

知道如何解决这个问题吗?

  // promise - search for workspace ...
  var promise = Space.findOne( spaceId ).exec();

  promise.then( function ( space ) {

     return Stack.findOne( { _id: req.params.id }, function( err , stack ) {
          stack.spaceTempName = space.name;
          stack.name = 'test';

          console.log( stack );
          return stack;
      });
  })
  .then( function ( stack ) {

      console.log( stack );
  })

【问题讨论】:

  • 我真的不明白这是一个重复的问题。
  • 好的,没有解释就不是 100% 清楚。简而言之,从 nodeback 返回一个值没有任何作用。从.then() 回调返回一个值会导致该值到承诺链中的下一个.then()。因此,为了使链按照您想要的方式运行,Stack.findOne() 需要按照参考案例 3 中描述的方式“承诺”。
  • 至少,这是解决问题的一般方法。 Vadi 的回答表明省略 nodeback 会导致 Stack.findOne() 返回一个承诺。如果确实如此,那么Stack.findOne() 已经为您有效地承诺了。只需省略 nodeback 即可获得所需的行为。

标签: javascript node.js mongoose promise bluebird


【解决方案1】:

您在此处使用回调 return Stack.findOne( { _id: req.params.id }, function,并返回 stack 而不更改下一个 then。您可以通过仅在该回调内部进行更改来获取 stack,或者在 Stack.findOne 之后添加 then

// promise - search for workspace ...
var promise = Space.findOne( spaceId ).exec();

promise.then( function (space) {

  return Stack.findOne( { _id: req.params.id })
    .then(function (stack) {
      stack.spaceTempName = space.name;
      stack.name = 'test';

      console.log(stack);
      return stack;
    })
    .catch(function (err) { console.log(err) });
})
.then( function (stack) {

  console.log(stack);
})
.catch(function(err) { console.log(err) });

或者为了可读性更好,你可以把它放到async函数中,使用await

const updateSpaceName = async (req, res) => {
  try {
    // promise - search for workspace ...
    promise = Space.findOne( spaceId ).exec();

    const space = await promise();

    const stack = await Stack.findOne( { _id: req.params.id } );

    stack.spaceTempName = space.name;
    stack.name = 'test';
    console.log( stack );

    // here you can pass stack to another promise
    // and it will have changed name
    await nextTestPromise(stack);

  } catch (err) {
    console.log(err);
  }
}

【讨论】:

  • stack 只会传播到第二个外部.then() 如果它是从嵌套的.then() 返回的。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 2016-03-04
  • 2021-10-22
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多