如何在虚拟字段getter函数中获取另一个模型数据|猫鼬

问题描述

我正在开发一个 MERN 堆栈项目,用户可以在其中对目标执行 CRUD 操作。我使用猫鼬进行对象建模。我想创建一个名为 stepAvgvirtual field 以通过使用步骤模型找出有关每个目标的一些信息。

关系信息

每个用户都有很多目标。

每个目标都有许多步骤。

GoalModel.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const StepModel = require("./StepModel");

const GoalSchema = new Schema({
    category: { type: Schema.ObjectId,ref: "Category",required: true },title: { type: String,startDate: { type: Date,completionDate: { type: Date,commitment: { type: String,obstacle: { type: String,default: null },celebration: { type: String,user: { type: Schema.ObjectId,ref: "User",steps: [{ type: Schema.Types.ObjectId,ref: "Step"}],},{
    toJSON: { virtuals: true },toObject: { virtuals: true }
},{timestamps: true});

GoalSchema.virtual('stepAvg').get(async function() {
    let steps = await StepModel.find({ goal: this.id }); 
    // if I console steps it return the data correctly.
    let totalSteps = steps.length;
    if (totalSteps) {
        let completedSteps = steps.filter(function(step) {
            return step.isCompleted;
        }).length;
        let avg = ( completedSteps / totalSteps) * 100;
        return avg;
    }
    return 0;
});

module.exports = mongoose.model("Goal",GoalSchema);

如您所见,我创建了一个虚拟字段 stepAvg,但每次它都会给我一个空对象。它实际上返回了承诺。

邮递员截图

Postman screenshot

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)