简体   繁体   中英

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. The basic gist of the schema is that of a simple Group object with a reference to a parent Group's ObjectId (parent_group).

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

The code for my Group schema definition looks like this:

// 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:

// 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:

{
    "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. I was unable to identify which validator is failing, but that could just be my unfamiliarity with debugging Mongoose.

It is also worth noting:

  • the ObjectId is correct
  • a null ObjectId works just fine
  • the error is being caught in 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 . Without looking into it too deeply, my understanding is that when joi validates the ObjectId as a string, it passes; 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.

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. I am currently using patch-package to maintain this patch in my application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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