node.js - 当架构中存在出生日期时,使用最大年龄和最小年龄过滤用户数据

标签 node.js mongodb mongoose-schema

我想根据最大年龄和最小年龄过滤用户数据,但我的用户架构中没有年龄字段。我有出生日期字段。我应该编写什么 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 查找年龄。在您要根据 MA​​X 或 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/

相关文章:

javascript - 尝试使用 setTimeout 在某些 js/node 代码中阻止 sleep

java - 异常来自 Collection 的不同值 - CurrentBSONType 是 UNDEFINED

用于 MongoDB 数据插入的 Spring 监听器

node.js - 如何使用 Mongoose 从 MongoDB 中的两个集合关系中查找计数

javascript - typeof 对象但不是数组

node.js - Google Closure 编译器移动了?它给出了 302 错误

node.js - Mongoose $near 填充被忽略

javascript - 更新 mongoose schema.save 中的 `let` 变量

javascript - 如何修复 "trim"在 Mongoose 模式中不起作用

javascript - 将选项传递给 gulp-jshint