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

我目前在尝试使用 Mongoose/Joigoose 将我的对象保存到 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 字符串,尝试在使用 转换后通过 JS 传递它mongoose.Types.ObjectId("5f32d6c58d0c4a080c48bc79"),但我一直收到相同的错误。我无法确定哪个验证器失败了,但这可能只是我不熟悉调试 Mongoose。

还值得注意的是:

  • ObjectId 正确

  • 一个空的 ObjectId 工作得很好

  • 错误被捕获在 model.save()

任何帮助将非常感激!


青春有我
浏览 96回答 1
1回答

慕沐林林

我的 ObjectId 验证失败的原因是joigoose 在幕后向 Mongoose 模式添加了 joi 验证器。无需深入研究,我的理解是,当 joi 将 ObjectId 验证为字符串时,它通过了;在 Mongoose 将 ObjectId 转换为对象而不是字符串(正如 joi 验证器所期望的那样)之后,这就是添加的验证器失败的地方。由于将 joi 验证器添加到 Mongoose 模式不是我想要的功能(我只是使用 joigoose 来整合模式),作为一个快速而肮脏的修复,我直接在我的本地副本中评论了 joigoose 中的那个部分。我目前正在使用补丁包在我的应用程序中维护这个补丁。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript