我想知道猫鼬中是否有一种简单的方法可以从模式中的相关出生日期获取一个人的年龄。
// Define the User schema
const Schema = mongoose.Schema;
const UserSchema = new Schema({
id: { type: Number, required: true, unique: true },
first_name: { type: String, required: true, max: [15, 'Too long name'] },
last_name: { type: String, required: true, max: [15, 'Too long surname'] },
gender: { type: String, required: true, enum: ['M', 'F'] },
image: { data: Buffer, contentType: String }
birthdate: { type: Date, required: true }
}, {
collection: 'Users'
});
如何实现?
// Virtual for user's age
UserSchema
.virtual('age')
.get(function() {
...
});
答案 0 :(得分:1)
您可以像下面这样操纵日期:
简短答案:
const birthdate = new Date(687882497000);
// replace birthdate by this.birthdate
const nbYearRounded = Math.floor((Date.now() - birthdate.getTime()) / (1000 * 3600 * 24 * 365));
console.log(nbYearRounded);
木乃伊:
const date = new Date(687882497000);
const timeInMs = date.getTime();
const diffInMs = Date.now() - timeInMs;
const nbDay = diffInMs / 1000 / 3600 / 24;
const nbYear = nbDay / 365;
const nbYearRounded = Math.floor(nbYear);
console.log(date);
console.log(timeInMs);
console.log(diffInMs);
console.log(nbDay);
console.log(nbYear);
console.log(nbYearRounded);
Here是有关 VirtualType.prototype.get()的文档。
给出示例:
var virtual = schema.virtual('fullname');
virtual.get(function () {
return this.name.first + ' ' + this.name.last;
});
答案 1 :(得分:0)
这应该有效
UserSchema.virtual('age').get(function(){
return Math.floor((Date.now() - this.birthdate.getTime()) / (1000 * 3600 * 24 * 365));
});