Reputation: 8268
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
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
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
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