如何解决如何在虚拟字段getter函数中获取另一个模型数据|猫鼬
我正在开发一个 MERN 堆栈项目,用户可以在其中对目标执行 CRUD 操作。我使用猫鼬进行对象建模。我想创建一个名为 stepAvg 的 virtual 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,但每次它都会给我一个空对象。它实际上返回了承诺。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。