node.js - 保存 Mongoose Schema 时如何检测字段名称拼写错误?
问题描述
我在 Mongoose Schema 中输入了一个错字,并且 POST 请求中的字段与数据库中的字段不匹配。所以 Mongoose 没有在文档中保存该字段。
表单有这个字段(在 PUG 中):
input(type="checkbox" id="happiness", name="happiness", value="true")
label(for="happiness") feels happier
Mongoose Schemas
在该字段中缺少一个:
'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,
// ...
}
happiness
因此,在req.body
没有警告的情况下,该字段被丢弃了。
如何确保req.body
对象中的每个字段都存在于 Mongoose 模式中?
解决方案
您可以使用该strict
选项。strict
选项默认启用,这将删除模式中不存在的字段,但您可以将其值设置为throw
会导致产生错误的值。
const QuestionnaireSchema = new Schema({}, {strict: 'throw'})
推荐阅读
- c# - 如何从文件存储中异步下载数百万个文件?
- php - 为什么当 nl2br 工作正常时 PHP_EOL 不工作
- azure-ad-b2c - 只有“电子邮件”字段可以通过“id_token_hint”传递给 B2C 自定义策略
- php - Google 日历 API 保持帐户连接
- c# - 如何使用 EditForm 将必填字段的日期默认为今天的日期?
- solr - 使用 curl 创建 solr 集合
- javascript - forEach 与 Firebase 调用
- c - 当程序期望C中的int时传递字符串
- r - http://localhost:8000/mapTiles/OSM/{z}_{x}_{y}.png 不工作 - SHINY R
- javascript - 复制后重新显示文本文件中的文本