首页 > 解决方案 > 保存 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 模式中?

标签: node.jsmongodbmongoose

解决方案


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

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

推荐阅读