【问题标题】:One to many save no response (promises)一对多保存没有响应(承诺)
【发布时间】:2019-02-21 11:36:10
【问题描述】:

我无法使用对象 ID 数组保存对象。我正在使用带有 restify 和 mongoose 的 node.js。

我有一个包含许多服装选择的服装请求:

型号:

const outfitRequestsSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  title: {
    type: String
  },
  maxCost: {
    type: Number
  },
  outfitChoices: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'OutfitChoice'
  }]
}, {usePushEach: true});

路由器:

application.post('/outfit-choices', (req, resp, next) => {
      OutfitRequest.findById(req.body.outfitRequest)
        .then(outfitRequest => {
          console.log(outfitRequest);
          const outfitChoice = new OutfitChoice(req.body);
          outfitChoice.save().then(outfitChoice => {
            outfitRequest.outfitChoices.push(outfitChoice._id);
            outfitRequest.save()
              .then(outfitRequestNew => {
                console.log(outfitRequestNew);
                this.render(resp, next);
              })
              .catch(next);

          }).catch(next);

        })
        .catch(next);
    });

渲染方法:

render(response: restify.Response, next: restify.Next) {
    return (document) => {
      if (document) {
        this.emit('beforeRender', document);
        response.json(document);
      } else {
        response.send(404);
      }

      return next();
    }
  }

Restlet screen

它保持循环,但记录保存在db中

DB screen

我认为这是链式 Promise 的问题,但我不知道如何解决。

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    我得到了这样的结果,我返回了最后一个承诺并将print 放入.then

     application.post('/outfit-choices', (req, resp, next) => {
              OutfitRequest.findById(req.body.outfitRequest)
                .then(outfitRequest => {
                  const outfitChoice = new OutfitChoice(req.body);
                  outfitChoice.save()
                    .then(outfitChoice => {
                    outfitRequest.outfitChoices.push(outfitChoice._id);
                    return outfitRequest.save()
                  })
                .then(this.render(resp, next))
                .catch(next);
    
                })
                .catch(next);
            });
    

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 2020-09-10
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2017-08-27
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多