【问题标题】:Can a Mongoose schema be inspected to determine if a field is required?是否可以检查 Mongoose 模式以确定是否需要某个字段?
【发布时间】:2012-10-17 21:50:44
【问题描述】:

我有一个 Mongoose 架构(摘录如下):

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

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

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

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

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

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    Mongoose 会为您进行此类验证。 http://mongoosejs.com/docs/validation.html.

    【讨论】:

    • 谢谢。这就是这样做的方法。
    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多