As stated here, I could see the improved schema validation errors for model.create()
but not for model.insertMany()
. The error format for model.insertMany()
is still the following. Does insertMany
not support improved format yet?
Env:
mongodb 5.0.6
mongoose 6.2.4
node v16.14.1
Schema:
{
"$jsonSchema": {
"bsonType": "object",
"additionalProperties": false,
"required": [
"name"
],
"properties": {
"_id": {
"bsonType": "objectId"
},
"name": {
"bsonType": "string"
}
}
}
}
Script that throws the following error:
const mongoose = require("mongoose");
main().catch((err) => {
console.log('error: ', JSON.stringify(err, null, 4));
process.exit(1);
});
async function main() {
await mongoose.connect("mongodb://localhost:27017/t12");
const schema = new mongoose.Schema({ name: String, value: String });
const model = mongoose.model("tests", schema);
let res;
res = await model.insertMany([{value: 'hello'}], { rawResult: true, ordered: false });
console.log('insert: ', res);
process.exit(0);
}
Error:
{
"code": 121,
"writeErrors": [
{
"code": 121,
"index": 0,
"errmsg": "Document failed validation",
"op": {
"value": "hello",
"_id": "62c5ae93986f65769edc60e7",
"__v": 0
}
}
],
"result": {
"ok": 1,
"writeErrors": [
{
"code": 121,
"index": 0,
"errmsg": "Document failed validation",
"op": {
"value": "hello",
"_id": "62c5ae93986f65769edc60e7",
"__v": 0
}
}
],
"writeConcernErrors": [],
"insertedIds": [
{
"index": 0,
"_id": "62c5ae93986f65769edc60e7"
}
],
"nInserted": 0,
"nUpserted": 0,
"nMatched": 0,
"nModified": 0,
"nRemoved": 0,
"upserted": []
},
"insertedDocs": []
}
CodePudding user response:
Mongoose passes the error received from the node.js mongodb driver. Following code shows how to find the schema validation error from the err.writeErrors
property.
Code:
main().catch((err) => {
// console.log('error: ', JSON.stringify(err, null, 4)); // -> this doesn't show errInfo where the schema validation errors are
console.log('error: ',JSON.stringify(err.writeErrors[0].errInfo,null,4));
process.exit(1);
});
async function main() {
const { MongoClient } = require("mongodb");
const schema = {
$jsonSchema: {
bsonType: "object",
additionalProperties: false,
required: ["name"],
properties: {
_id: {
bsonType: "objectId",
},
name: {
bsonType: "string",
},
},
},
};
const client = await MongoClient.connect("mongodb://localhost:27020", {
useNewUrlParser: true,
});
const db = client.db("t12");
await db.dropCollection("tests");
await db.createCollection("tests", { validator: schema });
await db.collection("tests").insertMany([{ value: "t2" }]); // should fail
await client.close();
}
Error:
error: {
"failingDocumentId": "62c64fcade43d36b7ebb3e58",
"details": {
"operatorName": "$jsonSchema",
"schemaRulesNotSatisfied": [
{
"operatorName": "additionalProperties",
"specifiedAs": {
"additionalProperties": false
},
"additionalProperties": [
"value"
]
},
{
"operatorName": "required",
"specifiedAs": {
"required": [
"name"
]
},
"missingProperties": [
"name"
]
}
]
}
}
CodePudding user response:
For people facing similar issues, you need to check what your featureCompatibilityVersion
, if it's anything below 5.0
then you're not going to get any of those detailed error reports. Would've been nice if MongoDB mentioned that somewhere in their docs or announcement article...
- Open
mongosh
and write:
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 })
// "4.4"
- Update
featureCompatibilityVersion
to5.0
db.adminCommand({ setFeatureCompatibilityVersion: "5.0" })
- Restart
mongod
.