【问题标题】:Mongoose's populate method breaks promise chain?Mongoose 的填充方法打破了承诺链?
【发布时间】:2014-12-29 15:48:24
【问题描述】:

所以我有一个看起来像这样的猫鼬模式:

var Functionary = new Schema({
  person: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Person'
  },
  dateOfAssignment: Date,
  dateOfDischarge: Date,
  isActive: Boolean
});

var PositionSchema = new Schema({
  name: String,
  description: String,
  maxHeadCount: Number,
  minHeadCount: Number,
  currentHeadCount: Number,
  currentlyHolding: [Functionary],
  historical: [Functionary],
  responsibleTo: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Position'
  }
});

*请注意,职位文档可以在ResponsibleTo 字段中引用自身。

现在,我正在尝试构建一个方法来搜索Positions 集合,填充currentlyHolding[].person.name fieldresponsibleTo.currentlyHolding[].person.name 字段,并返回找到的记录总数(用于前面的分页目的-结束)。

我的代码如下所示:

exports.search = function(req, res) {
  var result = {
    records: null,
    count: 0,
    currentPage: req.params.page,
    totalPages: 0,
    pageSize: 10,
    execTime: 0
  };

  var startTime = new Date();

  var populateQuery = [
    {
      path: 'currentlyHolding.person',
      select: 'name'
    }, {
      path:'responsibleTo',
      select:'name currentlyHolding.person'
    }
  ];

  Position.find(
    {
      $or: [
        { name: { $regex: '.*' + req.params.keyword + '.*', $options: 'i' } },
        { description: { $regex: '.*' + req.params.keyword + '.*', $options: 'i' } }
      ]
    },
    {},
    {
      skip: (result.currentPage - 1) * result.pageSize,
      limit: result.pageSize,
      sort: 'name'
    })
  .exec()
  .populate(populateQuery)
  .then(function(doc) {
    result.records = doc;
  });

  Position.count(
    {
      $or: [
        { name: { $regex: '.*' + req.params.keyword + '.*', $options: 'i' } },
        { description: { $regex: '.*' + req.params.keyword + '.*', $options: 'i' } }
      ]
    })
  .exec()
  .then(function(doc) {
    result.count = doc;
    result.totalPages = Math.ceil(result.count / result.pageSize);
  })
  .then(function() {
    var endTime = new Date();
    result.execTime = endTime - startTime;
    return res.json(200, result);
  });
};

我的问题是当我使用 populate 方法运行第一个查询时(如图所示),它不起作用。我带走了人口,它起作用了。 populate 方法会破坏承诺,这是真的吗?如果是这样,有没有更好的方法来实现我想要的?

【问题讨论】:

    标签: express mongoose mongoose-populate


    【解决方案1】:

    您已经有一段时间没有问过了,但这可能仍然对其他人有所帮助,所以我们开始吧:

    According to the docs, .populate() 不返回承诺。为此,您应该链接.execPopulate()

    或者,您可以将.populate() 放在.exec() 之前。后者将终止查询构建器界面并为您返回一个承诺。

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2017-08-06
      • 2017-11-23
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      相关资源
      最近更新 更多