21

On MongoDB 3.4.4 I've created a collection with a validator, but now some inserts fail this rules and I can't understand why.

  1. Is there a way to output the rules of the validor? I'm afraid the rules applied are different from what I think they are...
  2. Is there a way to improve the error message? "Document failed validation" in this scenario is quite useless.

Thank you!

1
  • 1
    using pymongo: db.get_collection('test').options().get('validator') Commented Jul 16, 2021 at 8:38

3 Answers 3

32
  1. You can see the validation rules (among other collection information) with db.getCollectionInfos() for all collections or db.getCollectionInfos({name: "myCollection"}) for a specific collection: MongoDB docs

  2. Have a look at this answer.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also view validation rules in the MongoDB Compass GUI
0

For Node.js mongodb client, one has to call db.getCollections.

Comments

0

With NodeJS, TypeScript and [email protected] you could use this code:

import { CollectionInfo, Client, MongoClient } from "mongodb";

const getCollInfo = async (client: Client, name: string) => {
    const colls = await client.db.listCollections({ name }).toArray();
    return colls?.[0];
};

const client = await MongoClient.connect("mongodb://localhost:27017/db");
const info = await getCollInfo(client, "user") as CollectionInfo;
const validator = info.options?.validator;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.