Mongoose 中的人年龄虚拟财产
Posted
技术标签:
【中文标题】Mongoose 中的人年龄虚拟财产【英文标题】:Person Age Virtual Property in Mongoose 【发布时间】:2018-12-01 23:32:10 【问题描述】:我想知道 Mongoose 中是否有一种简单的方法可以从架构中的相关生日获取一个人的年龄。
// 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()
...
);
【问题讨论】:
【参考方案1】:这应该可以工作
UserSchema.virtual('age').get(function()
return Math.floor((Date.now() - this.birthdate.getTime()) / (1000 * 3600 * 24 * 365));
);
【讨论】:
【参考方案2】:您可以像下面这样操作日期:
简答:
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;
);
【讨论】:
以上是关于Mongoose 中的人年龄虚拟财产的主要内容,如果未能解决你的问题,请参考以下文章