1
votes

I want to create a virtual 'passed' value of a schema to do so I need to check another schema to see if two values match.

had a look online and you can populate the ref during a query but haven't seen any examples of doing it directly in a schema

var ExerciseSchema = new Schema({
  title: { type: String, required: true },
  output: [{ type: String, required: true }]
});

export var Exercise = mongoose.model('Exercise', ExerciseSchema);

I want to compare the output of the ExerciseSchema with the output from AttemptSchema and return true or false using the virtual 'passed' variable

var AttemptSchema = new Schema({
  exercise: { type: ObjectId, ref: 'Exercise', required: true },
  output: [{ type: String }],
});

export var Attempt = mongoose.model('Attempt', AttemptSchema);

AttemptSchema.virtual('passed').get(function() {
  // compare outputs to see if passed
});
1
When do you want passed to be true or false? Do you want it to be true if the output arrays are equal (contains the same items in the same position)?VirgilioGM
i want it to return true is the output arrays from both schema's are the same. my plan is to just convert them both to strings for the check but don't know how to access the ref variables or if u even can from a virtual variable.Andrew Dean

1 Answers

2
votes

I think your virtual field definition should be something like this:

AttemptSchema.virtual('passed').get(function() {
    var attemptOutput = this.output.join();
    mongoose.model('Exercise').findById(this.exercise, function(err, excercise) {
        return excercise.output.join() === attemptOutput;
    });
});