如何解决使用Mongoose保存到MongoDB时,ObjectId作为字符串失败
当我尝试使用Mongoose / Joigoose将对象保存到MongoDB时,我当前收到验证错误。该模式的基本要点是一个简单的Group对象,该对象引用父组的ObjectId(parent_group)。
这是错误:
ValidationError: parent_group: Validator failed for path 'parent_group' with value '5f32d6c58d0c4a080c48bc79'
我的组架构定义的代码如下:
// Imports (for reference)
const mongoose = require('mongoose'); // v5.9.29
const Joigoose = require('joigoose')(mongoose); // v7.1.2
const Joi = require('@hapi/joi'); // v17.1.1
const uniqueValidator = require('mongoose-unique-validator'); // v2.0.3
const ObjectId = mongoose.Schema.Types.ObjectId;
// Schema
const joiGroupSchema = Joi.object().keys({
id: Joi.string().required().meta({ _mongoose: { unique: true }}).regex(/^[\w-]+$/).max(50),name: Joi.string().required().max(50),notes: Joi.string().allow(null),parent_group: Joi.string().allow(null).regex(/^[0-9A-Fa-f]*$/).max(24).meta({ _mongoose: { type: ObjectId,ref: 'Group' }}),}).options({stripUnknown: true});
const groupSchema = new mongoose.Schema(Joigoose.convert(joiGroupSchema));
groupSchema.plugin(uniqueValidator);
const Group = mongoose.model("Group",groupSchema);
我的猫鼬保存呼叫如下:
// This code is inside of an Express HTTP POST definition (hence the result.value and req/res)
let model = new Group(result.value);
model.save(function (err,doc) {
// On error
if (err) {
if (err.errors.id && err.errors.id.properties.type == 'unique') {
res.status(409);
return res.send('POST failed');
}
res.status(500);
return res.send('POST failed');
}
res.status(200);
return res.send('success');
});
我使用Postman传递的数据如下:
{
"id": "asdf","name": "ASDF","notes": "postman","parent_group": "5f32d6c58d0c4a080c48bc79"
}
我尝试了不同格式的parent_group字符串,使用mongoose.Types.ObjectId("5f32d6c58d0c4a080c48bc79")
转换后尝试通过JS传递,但是我仍然收到相同的错误。我无法确定哪个验证程序失败,但这可能只是我不熟悉调试Mongoose。
这也值得注意:
- ObjectId是正确的
- 空的ObjectId可以正常工作
- 在model.save()中捕获了错误
任何帮助将不胜感激!
解决方法
我的ObjectId验证失败的原因是joigoose adds joi validators to the Mongoose schema behind the scenes。不用太深入研究,我的理解是,当joi将ObjectId验证为字符串时,它会通过;在Mongoose将ObjectId转换为对象而不是字符串(如joi验证程序期望的那样)之后,这就是添加的验证程序失败的地方。
由于我不希望将joi验证器添加到Mongoose架构中(我只是使用joigoose来整合架构),因此,为了快速解决此问题,我在joigoose的本地副本中直接评论了该部分。它。我当前正在使用patch-package在我的应用程序中维护此补丁。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。