【问题标题】:How to detect field name typo when saving a Mongoose Schema?保存 Mongoose Schema 时如何检测字段名称拼写错误?
【发布时间】:2021-03-09 21:23:42
【问题描述】:

我在 Mongoose Schema 中输入了一个错字,而 POST 请求中的字段与数据库中的字段不匹配。所以 Mongoose 没有在文档中保存该字段。

表单有这个字段(在 PUG 中):

input(type="checkbox" id="happiness", name="happiness", value="true")
label(for="happiness") feels happier

Mongoose 架构在该字段中缺少 s

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Use native promises.
mongoose.Promise = global.Promise;

// Define the schema.
const QuestionnaireSchema = new Schema({

  happines: Boolean,
  // ...
}

因此req.body 中的字段happiness 被丢弃而没有警告。

如何确保 req.body 对象中的每个字段都存在于 Mongoose 架构中?

【问题讨论】:

  • 为 mongoose 模式中的所有字段设置 requiredtrue
  • 为复选框输入设置required 需要用户标记复选框,但这是一个可选字段。

标签: node.js mongodb mongoose


【解决方案1】:

您可以使用strict 选项。 strict 选项默认启用,这将删除架构中不存在的字段,但您可以将其值设置为 throw,这将导致产生错误。

const QuestionnaireSchema = new Schema({}, {strict: 'throw'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2010-10-16
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多