node.js - 是否可以检查 Mongoose 模式以确定是否需要某个字段?

标签 node.js mongoose

我有一个 Mongoose 模式(摘录如下):

var PersonSchema = new Schema({
  name : { 
      first: { type: String, required: true } 
    , last: { type: String, required: true }   
  } 
  ...

我想检查架构以确定哪些字段是必需的,然后验证这些字段是否存在于用户输入中。我可以测试 name.first 的 'required' 属性,如下所示:

var person_schema = require('../models/person');

if (person_schema.schema.paths['name.first'].isRequired) {
  req.assert('first', messages.form_messages.msg_required).notEmpty();

但是感觉这是不安全的,因为内部架构细节可能会改变。有没有更好的办法?

最佳答案

Mongoose 为您进行这种类型的验证。 http://mongoosejs.com/docs/validation.html .

关于node.js - 是否可以检查 Mongoose 模式以确定是否需要某个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12934080/

相关文章:

rest - 使用 Mongoose 进行错误处理

node.js - GeoJSON 在 Node.js 中与 Mongoose/Mongodb 配合使用

javascript - socket.io 分配自定义 socket.id

javascript - PassportJS/Express 内部出错后如何重定向?

node.js - Jest/Ts-Jest/Babel : Debug Failure. 错误表达式:输出生成失败

arrays - MongoDB 对象属性 $ 存在于嵌套数组中

javascript - MongoDB Mongoose 使用数组保存或更新

javascript - 如何查询和过滤 Firebase 实时数据库

javascript - Meteor 发送给活跃用户

arrays - 在 Mongo 中,映射数组并更新文档