我想根据最大年龄和最小年龄过滤用户数据,但我的用户架构中没有年龄字段。我有出生日期字段。我应该编写什么 Mongoose 查询才能获得所需的结果。
const userSchema = new mongoose.Schema({
name: { type: String, required: false },
bnr: {type: String, required: false},
firstname : {type: String, required: false},
lastname : {type: String, required: false},
profilepic: String,
dob: {type: Date, required:true}
},{timestamps: true}}
最佳答案
您可以使用自定义函数通过 DOB 查找年龄。在您要根据 MAX 或 MIN 筛选年龄的筛选函数中,从 Controller 调用此函数:
function getAge(DOB) {
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age = age - 1;
}
return age;
}
这将返回年龄。例如,我正在创建一个虚拟函数:
function filter(res, req, next){
var age = getAge(res.DOB);
//and the your max or min calculations...
}
关于node.js - 当架构中存在出生日期时,使用最大年龄和最小年龄过滤用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497368/