Mongoose 所需的验证器失败值未定义
Posted
技术标签:
【中文标题】Mongoose 所需的验证器失败值未定义【英文标题】:Mongoose required validator fails value is undefined 【发布时间】:2019-12-15 14:24:46 【问题描述】:我尝试将数据保存在猫鼬模式中,但所需的验证器失败,错误消息说该值未定义,但之前的日志表明它有一个值。
我尝试使用新的 mongoose.Schema 而不是新的 Schema,但效果不佳。
当我删除所需的标签时,它会保存但它是空的: bookingNumber: _id: 5d4b47d7685936130080eb70, __v: 0
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookingNumberSchema = new Schema(
number:
type: Number,
required: true,
,
description:
type: String,
required: true,
,
);
const BookingNumber = mongoose.model('BookingNumber', BookingNumberSchema);
module.exports = BookingNumber;
function createBookingNumber(req, res)
console.log(req.body);
BookingNumber.create(req.body)
.then(bookingNumber =>
let reply =
"bookingNumber": bookingNumber
res.status(200);
console.log(reply);
res.send(reply);
)
.catch(err =>
res.status(400);
console.log(err);
res.send(err);
);
在我的 app.js 中,我使用 bodyParser.json 并过滤 nosql 攻击:
app.use(bodyParser.json());
app.use(filter());
邮递员数据:
"bookingNumber":
"number": 1,
"description": "example bookingnumber"
回复:
"errors":
"description":
"message": "Path `description` is required.",
"name": "ValidatorError",
"properties":
"message": "Path `description` is required.",
"type": "required",
"path": "description"
,
"kind": "required",
"path": "description"
,
"number":
"message": "Path `number` is required.",
"name": "ValidatorError",
"properties":
"message": "Path `number` is required.",
"type": "required",
"path": "number"
,
"kind": "required",
"path": "number"
,
"_message": "BookingNumber validation failed",
"message": "BookingNumber validation failed: description: Path `description` is required., number: Path `number` is required.",
"name": "ValidationError"
console.log:
bookingNumber: number: 1, description: 'example bookingnumber'
ValidationError: BookingNumber validation failed: description: Path `description` is required., number: Path `number` is required.
message: 'Path `description` is required.',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'description',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true ,
number:
我看起来输入值没有传递给猫鼬,但我找不到原因。
【问题讨论】:
【参考方案1】:在您发送数据的邮递员中:
"bookingNumber":
"number": 1,
"description": "example bookingnumber"
并且您的架构 BookingNumber 没有像您发送带有嵌套对象的“bookingNumber”那样的键,mongoose 验证器没有检查“编号”并且没有“描述”,这就是您的请求失败的原因。 只需发送如下:
"number": 1,
"description": "example bookingnumber"
【讨论】:
以上是关于Mongoose 所需的验证器失败值未定义的主要内容,如果未能解决你的问题,请参考以下文章
Wildfly 11 Elytron - 基于属性文件的身份验证失败,未安装所需的服务
javascript:我的代码应该从60开始倒数 ,但数字值未出现