Andranik Hayrapetyan
Andranik Hayrapetyan

Reputation: 43

Mongoose conditional field value

I am working on a project with NodeJS and MongoDB and I am using Mongoose. In my database I am storing the companies with the opening and closing hours. I also have a field isOpen which is a boolean and I want to know if it's possible to dynamically change the value of isOpen in mongoDB according to current date and the the opening hours of the company.

{
    openingHours {
        opens: Number,
        closes: Number
    },
    isOpen: Boolean // should depend on the current date and openinghours
}

PS: I saw that it was possible to put a function over the field required.

Upvotes: 4

Views: 1904

Answers (1)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5708

You could use virtual property to get that functionality.

var storeSchema = new Schema({
  openingHours {
        opens: Number,
        closes: Number
  },
});

storeSchema.virtual('isOpen').get(function () {
  const currentTime = Date.now();
  const currentHour = currentTime.getHours();
  return this.openingHours.opens >= currentHour && currentHour < this.openingHours.closes;
});

More information about virtual property you can find in official documentation.

Upvotes: 1

Related Questions