[英]Saving to MongoDB using Mongoose fails on ObjectId as string
我目前在嘗試使用 Mongoose/Joigoose 將我的 object 保存到 MongoDB 時收到驗證錯誤。 該模式的基本要點是一個簡單的組 object 並引用了父組的 ObjectId (parent_group)。
這是錯誤: ValidationError: parent_group: Validator failed for path 'parent_group' with value '5f32d6c58d0c4a080c48bc79'
我的 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);
我的 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');
});
我使用 Postman 傳遞的數據如下所示:
{
"id": "asdf",
"name": "ASDF",
"notes": "postman",
"parent_group": "5f32d6c58d0c4a080c48bc79"
}
我嘗試了不同格式的 parent_group 字符串,嘗試在使用mongoose.Types.ObjectId("5f32d6c58d0c4a080c48bc79")
轉換后通過 JS 傳遞它,但我一直收到相同的錯誤。 我無法確定哪個驗證器失敗了,但這可能只是我不熟悉調試 Mongoose。
同樣值得注意的是:
任何幫助將非常感激!
我的 ObjectId 驗證失敗的原因是joigoose 在幕后將 joi 驗證器添加到 ZCCADCDEDB567ABAE643E15DCF0974E503Z 架構中。 沒有深入研究它,我的理解是當 joi 將 ObjectId 驗證為字符串時,它通過了; 在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 將 ObjectId 轉換為 object 而不是字符串之后(正如 joi 驗證器所期望的那樣),這就是添加的驗證器失敗的地方。
由於將 joi 驗證器添加到 Mongoose 模式不是我想要的功能(我只是使用 joigoose 來整合模式),因此作為一種快速而骯臟的修復,我直接在我的本地副本中評論了 joigoose 中的該部分。 我目前正在使用補丁包在我的應用程序中維護此補丁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.