Vlad
Vlad

Reputation: 8268

Is there such a thing as JSON schema for MongoDB query language itself?

MongoDB queries--at least in JavaScript--are structured as JSON, but it's very flexible so I am aware this wouldn't be a simple thing to do and in fact not even sure if this is possible, but was just wondering.

Is there a JSON schema to detect if a random JSON is a valid MongoDB query object?

Upvotes: 10

Views: 1153

Answers (4)

Katya Kamenieva
Katya Kamenieva

Reputation: 376

You may validate that the structure is valid, but if you want to know if the query is actually correct, like has the right syntax and can be executed - then no, not really.

Upvotes: 0

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

You can use any of the following packages

mongodb-language-model

mongodb-query-parser

Upvotes: 0

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

You can use something like mongodb-language-model

How to use

var accepts = require('mongodb-language-model').accepts;

console.log(accepts('{"ns":{"$in":["foo", "bar", "baz"]}}'));  // true
console.log(accepts('{"ns":{"$in":{}}}'));                     // false
console.log(accepts('{"ns":{"$regex": "foo"}}'));              // true

Upvotes: 2

Developer Ol
Developer Ol

Reputation: 112

It seems like the MongoDB Compass has (at least partly) implemented a Query Language verification for many commands like $or, $and $text / $search etc. Compass does not simply check if your query is a valid JSON, but also validates that you provided a correct query format. If you are interested in how it has been implemented I would recommend you to check the github sourcecode.

Upvotes: 0

Related Questions