the holla
the holla

Reputation: 816

is it possible to define document values based on other values in mongoose schema?

I have a limit and count on a model schema. I would like to have a boolean reachedLimit become true once those two values are equal. Is there a way to calculate this automatically in the model or do I need to do it manually?

I tried the below code and it always returns true. Even if it returned false as expected, I think it would assign reachedLimit a default value on creation, and then never reassign the value. What is the best way to dynamically check for equality on the model?

const invitationSchema = new Schema({
    limit: { type: Number, default: 1 },
    count: { type: Number, default: 0 },
    reachedLimit: { type: Boolean, default: {
        $eq: ['$limit', '$count'],
    } },
});

Upvotes: 0

Views: 574

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312095

You can do this by adding reachedLimit as a virtual in your schema:

const invitationSchema = new Schema({
    limit: { type: Number, default: 1 },
    count: { type: Number, default: 0 }
});
invitationSchema.virtual('reachedLimit').get(function() {
    return this.limit === this.count;
});

As the name implies, this won't actually add the field to your saved documents, but is generated as an additional property when querying documents.

Upvotes: 2

Related Questions