【问题标题】:Mongoose schema set min and max datesMongoose 模式设置最小和最大日期
【发布时间】:2021-06-29 19:38:30
【问题描述】:

我想创建一个“事件”对象,显然事件需要在某个日期发生,我希望用户:

  1. 没有设置过去的日期,
  2. 未来不少于 1 天(尚未尝试实施)
  3. 未来不超过 3 个月

很确定我需要一个函数,下面的代码显然不起作用。

const mongoose = require("mongoose");


const eventSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 1,
    maxlength: 50,
    unique: true,
  },
  date: {
    type: Date,
    required: true,
    min: Date.now - 24 * 60 * 60 * 1000,
    max: Date.now + 90 * 24 * 60 * 60 * 1000,
  }

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我设法弄明白了, 使用 javascript getTime() 方法以毫秒为单位获取时间戳,然后将其与未来的点(也以毫秒为单位)进行比较。

    const mongoose = require("mongoose");     
    
    const eventSchema = new mongoose.Schema({
          date: {
            type: Date,
            required: true,
            validate: {
              validator: function (v) {
                return (
                  v && // check that there is a date object
                  v.getTime() > Date.now() + 24 * 60 * 60 * 1000 &&
                  v.getTime() < Date.now() + 90 * 24 * 60 * 60 * 1000
                );
              },
              message:
                "An event must be at least 1 day from now and not more than 90 days.",
            }
          }})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多