node.js - Mongoose 条件字段值

标签 node.js mongodb mongoose

我正在使用 NodeJS 和 MongoDB 开发一个项目,我正在使用 Mongoose。在我的数据库中,我存储了公司的营业时间和营业时间。我还有一个 isOpen 字段,它是一个 bool 值,我想知道是否可以根据当前日期和开放时间动态更改 mongoDB 中 isOpen 的值公司的。

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

PS:我看到可以在字段 required 上放置一个函数。

最佳答案

您可以使用虚拟属性(property)来获得该功能。

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;
});

有关虚拟属性(property)的更多信息,您可以在 official documentation 中找到.

关于node.js - Mongoose 条件字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55296455/

相关文章:

node.js - 使用 Node.JS 和 CouchDB 的离线应用程序

javascript - 通过mongoose访问数组元素

node.js - 在node.js中实现互斥

javascript - 使用 express 发送后出现错误无法设置 header ?

javascript - 如何防止 socket.io 顺序/自动发出事件?

mongodb - 为什么 serverstatus 对 mongod 写操作有不好的影响?

node.js - 错误 : Please install tedious package manually

node.js - 合并聚合并在 MongoDB 中查找结果

node.js - 更新并指定 addToSet 的键

node.js - "How to get ' 父级到子级 ' relation with mongodb aggregation"