2014-11-03 49 views
2

所以我有一个猫鼬架构,看起来像这样:Mongoose的填充方法打破了承诺链?

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方法,第一个查询(如图所示),这是行不通的。我拿走了人口和它的作品。填充方法是否会破坏诺言是真的吗?如果是这样,是否有更好的方法来实现我想要的?

回答

0

这已经有一段时间,因为你问,但是这可能仍然帮助别人所以在这里,我们去:

According to the docs.populate()不返回的承诺。要发生这种情况,你应该链接.execPopulate()

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