mongodb - 如何向 Mongoose 模式子字段添加时间戳?

标签 mongodb mongoose mongoose-schema

我正在尝试添加 createdAtupdatedAt otp 的子字段中的时间戳在 generate: {}verify:{}我知道使用 { timestamps: true }将添加 createdAtupdatedAt整个架构的时间戳。`

const userSchema = new mongoose.Schema({    
    email: { type: String, unique: true },
    name: { type: String }, 
    mobileNumber: {
        isVerified: {type: Boolean, default: false},
        otp: {
            generate: {
              attempts: {type: Number, default: 0},
              total: {type: Number, default: 0},
              createdAt: {type: Date},
              updatedAt: {type: Date}
            },
            verify: {
              attempts: {type: Number, default: 0},
              total: {type: Number, default: 0},
              createdAt: {type: Date},
              updatedAt: {type: Date}
            }
          }
    }
}, { timestamps: true });
将单个时间戳添加到子字段的正确解决方案是什么?通过添加 {timestamps: true} 来做同样的事情是否正确?到子字段?
            generate: {
              attempts: {type: Number, default: 0},
              total: {type: Number, default: 0},
              {timestamps: true}
            },
            verify: {
              attempts: {type: Number, default: 0},
              total: {type: Number, default: 0},
              {timestamps: true}
            }

最佳答案

您必须为子字段定义单独的架构,然后将其用作子字段的类型。

const otpSchema = new mongoose.Schema({    
    attempts: { type: Number, default: 0 },
    total: { type: Number, default: 0 }
}, {
    _id: false, // omit _id fields for subfields
    timestamps: true // timestamps options for subfields
});

const userSchema = new mongoose.Schema({    
    email: { type: String, unique: true },
    name: { type: String }, 
    mobileNumber: {
        isVerified: { type: Boolean, default: false },
        otp: {
            generate: otpSchema, // use the defined schema
            verify: otpSchema
        }
    }
}, { timestamps: true });

关于mongodb - 如何向 Mongoose 模式子字段添加时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62977227/

相关文章:

node.js - 如何访问函数外部的变量

angularjs - mongo/mongoose 查询查找删除空间的字段

javascript - Mongod 无法正常运行

python - 导入 Eve,但运行 run.py 时,显示没有名为 eve 的模块

MongoDB 使用索引搜索空的 objectId 字段的有效方法?

node.js - MongoDB 不使用 NodeJS 驱动程序应用程序返回数据

node.js - 根据 Mongoose 模式验证对象而不另存为新文档

javascript - Mongoose 使用 float 作为键

node.js - 如何为子文档创建 mongoDb 模式

regex - 整数值的 MongoDB 正则表达式搜索