I am working on a MERN stack project where A user can perform CRUD operations on Goals. I use mongoose for object modeling. I want to create a virtual field named stepAvg to find out some information about each goal by using the step model.
Relationship information
Each user has many goals.
Each goal has many steps.
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, required: true },
startDate: { type: Date, required: true },
completionDate: { type: Date, required: true },
commitment: { type: String, required: true },
obstacle: { type: String, default: null },
celebration: { type: String, default: null },
user: { type: Schema.ObjectId, ref: "User", required: true },
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);
As you can see I create a virtual field stepAvg but every time it gives me the empty object. It actually returns the promise.
