使用Mongoose将ObjectId作为字符串保存到MongoDB失败



当我试图使用Mongoose/Joigose将我的对象保存到MongoDB时,我当前收到一个验证错误。模式的基本要点是一个简单的Group对象,它引用了父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在后台向Mongoose模式添加了joi验证器。在不深入研究的情况下,我的理解是,当joi将ObjectId验证为字符串时,它会通过;在Mongoose将ObjectId转换为对象而不是字符串(正如joi验证器所期望的那样(之后,添加的验证器就会失败。

由于在Mongoose架构中添加joi验证器不是我想要的功能(我只是使用joigoose来整合架构(,作为一个快速而肮脏的修复,我直接在我的本地副本中评论了该部分。我目前正在使用补丁包在我的应用程序中维护该补丁。

最新更新