使用Mongoose在模型中获取单个属性

时间:2015-11-09 02:52:23

标签: mongodb mongoose

我有2个架构:StepSchema,StepRelationshipSchema

var StepSchema = new Schema(
    {        
        name:           { type: String, required: true },
        description:    { type: String, default: '' },
        isVisible:      { type: Boolean, default: true }
    }, options
);


var StepRelationshipSchema = new Schema(
    {        
        workflowId:     { type: String, required: true },
        stepId:         { type: String, required: true },
        prevSteps:      [ Schema.Types.Mixed ] ,
        nextSteps:      [ Schema.Types.Mixed ] ,
        gotoStep:       { type: String, default: '' }
    }, options
);

在StepSchema中,我想创建一个静态方法来获取StepRelationshipSchema中的nextSteps。 我可以用这个,非常感谢你。

StepSchema.statics.getNextSteps = function(workflowId, currStepId) {
    return StepRelationship.findOne({
        workflowId: workflowId,
        stepId:     currStepId
    }).nextSteps
};

1 个答案:

答案 0 :(得分:0)

正如@JohnnyHK在评论中建议的那样, findOne() 是异步的,因此您需要使用如下的回调函数:

// create a query for next stepswith a blogpost _id matching workflowId and currStepId
schema.statics.getNextSteps = function (workflowId, currStepId, callback) {
    return this.model('StepRelationship').findOne({
        workflowId: workflowId,
        stepId:     currStepId
    }, callback);
}