简体   繁体   English

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

[英]Saving to MongoDB using Mongoose fails on ObjectId as string

I'm currently receiving a validation error when trying to save my object to MongoDB using Mongoose/Joigoose.我目前在尝试使用 Mongoose/Joigoose 将我的 object 保存到 MongoDB 时收到验证错误。 The basic gist of the schema is that of a simple Group object with a reference to a parent Group's ObjectId (parent_group).该模式的基本要点是一个简单的组 object 并引用了父组的 ObjectId (parent_group)。

Here's the error: ValidationError: parent_group: Validator failed for path 'parent_group' with value '5f32d6c58d0c4a080c48bc79'这是错误: ValidationError: parent_group: Validator failed for path 'parent_group' with value '5f32d6c58d0c4a080c48bc79'

The code for my Group schema definition looks like this:我的 Group 架构定义的代码如下所示:

// 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);

My mongoose save call looks like this:我的 mongoose 保存调用如下所示:

// 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');
});

The data I'm passing using Postman looks like this:我使用 Postman 传递的数据如下所示:

{
    "id": "asdf",
    "name": "ASDF",
    "notes": "postman",
    "parent_group": "5f32d6c58d0c4a080c48bc79"
}

I've tried different formats of the parent_group string, tried passing it through JS after converting it using mongoose.Types.ObjectId("5f32d6c58d0c4a080c48bc79") , but I keep receiving the same error.我尝试了不同格式的 parent_group 字符串,尝试在使用mongoose.Types.ObjectId("5f32d6c58d0c4a080c48bc79")转换后通过 JS 传递它,但我一直收到相同的错误。 I was unable to identify which validator is failing, but that could just be my unfamiliarity with debugging Mongoose.我无法确定哪个验证器失败了,但这可能只是我不熟悉调试 Mongoose。

It is also worth noting:同样值得注意的是:

  • the ObjectId is correct ObjectId 是正确的
  • a null ObjectId works just fine一个 null ObjectId 工作得很好
  • the error is being caught in model.save()错误被捕获在 model.save()

Any help would be much appreciated!任何帮助将非常感激!

The reason my ObjectId was failing validation is joigoose adds joi validators to the Mongoose schema behind the scenes .我的 ObjectId 验证失败的原因是joigoose 在幕后将 joi 验证器添加到 ZCCADCDEDB567ABAE643E15DCF0974E503Z 架构中 Without looking into it too deeply, my understanding is that when joi validates the ObjectId as a string, it passes;没有深入研究它,我的理解是当 joi 将 ObjectId 验证为字符串时,它通过了; after Mongoose converts the ObjectId to an object rather than a string (as the joi validator was expecting), that's where the added validator fails.在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 将 ObjectId 转换为 object 而不是字符串之后(正如 joi 验证器所期望的那样),这就是添加的验证器失败的地方。

Since adding joi validators to Mongoose schema is not a functionality that I want (I am just using joigoose to consolidate schemas), as a quick-and-dirty fix, I commented that section out of joigoose directly in my local copy of it.由于将 joi 验证器添加到 Mongoose 模式不是我想要的功能(我只是使用 joigoose 来整合模式),因此作为一种快速而肮脏的修复,我直接在我的本地副本中评论了 joigoose 中的该部分。 I am currently using patch-package to maintain this patch in my application.我目前正在使用补丁包在我的应用程序中维护此补丁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM