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

mongoosejs返回一个带有更改对象的model.find

运维笔记admin8浏览0评论

mongoosejs返回一个带有更改对象的model.find

mongoosejs返回一个带有更改对象的model.find

我有一个问题,即查询我的猫鼬模型并将更改的对象传递给下一个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 );
  })
回答如下:

你在这里使用回调return Stack.findOne( { _id: req.params.id }, function,并返回stack而不改变下一个then。你可以通过回调内部的变化获得stack,或者在then之后添加Stack.findOne

// 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);
  }
}
发布评论

评论列表(0)

  1. 暂无评论