So I have an MEAN stack application where user types query ( or copy from mongodb compass ) in a editor and I use nodejs in backend to perform that query ,

So I use codemirror editor to text codes , currently I enabled javascript editor to allow users to type ObjectId , as sometimes user type query in Mongodb compass and paste here in input so how can I safely convert the js object to mongodb query

 initJsonEditor() {
    if (this.jsonEditorView) {
      this.jsonEditorView.destroy();
    }

    let editorTarget: ElementRef | null = null;
    let form: FormGroup | null = null;

    if (this.selected_widget_type === DASHBOARD_CONSTANTS.html_content) {
      editorTarget = this.htmlQueryEditor;
      form = this.html_form;
    } else if (this.selected_widget_type === DASHBOARD_CONSTANTS.chart) {
      editorTarget = this.chartQueryEditor;
      form = this.chart_form;
    } else if (this.selected_widget_type === DASHBOARD_CONSTANTS.table) {
      editorTarget = this.tableQueryEditor;
      form = this.table_form;
    }

    if (!editorTarget?.nativeElement) {
      setTimeout(() => this.initJsonEditor(), 50);
      return;
    }

    if (!editorTarget || !form) return;
    this.jsonEditorErrorMessage = null;

    this.jsonEditorView = new EditorView({
      parent: editorTarget.nativeElement,
      state: EditorState.create({
        doc: form.get("query")?.value || "",
        extensions: [
          basicSetup,
          oneDark,
          javascript({
            jsx : false,
            typescript : false,
          }),
          lintGutter(),
          // this.jsonLint(),
          EditorView.updateListener.of((update) => {
            if (update.docChanged) {
              form.get("query")?.setValue(update.state.doc.toString());
            }
          }),
        ],
      }),
    });
  }

Above code ifor my editor for codemirror as in js

And while submitting form I checking that parse as it's valid


const fn = new Function (
const ObjectId = (id) => ( { $oid : id });

return query 
)

The above code is works but if I type { $oid then I get error as I wrap that code in try catch so , is there any way that I can parse safely and correctly

1 Reply 1

You generally should not try to run a user-provided JavaScript object (containing e.g. ObjectId(...)) via new Function() — that is unsafe, error-prone, and can be exploited. Instead you should parse/validate a safe representation (e.g. JSON or “extended JSON”), then translate it properly into a MongoDB query object.

A recommended approach will be to use Extended JSON or canonical JSON + convert fields

  1. Require clients to submit queries as valid JSON (or Extended JSON), not arbitrary JS code.

    • For example a string like:

      {
        "_id": { "$oid": "604c1c2f5f1b2c3a4d5e6f7g" },
        "status": "active"
      }
      
      
    • Then parse with JSON.parse() (or equivalent).

  2. After parse, convert fields like $oid into actual ObjectId instances before passing to MongoDB driver:

    const input = JSON.parse(userInput);
    // A simple recursive walk — or use a library like `mongodb-extended-json`
    function convertExtendedJSON(obj) {
      if (obj && typeof obj === 'object') {
        if (obj.$oid && typeof obj.$oid === 'string') {
          return new ObjectId(obj.$oid);
        }
        for (const key of Object.keys(obj)) {
          obj[key] = convertExtendedJSON(obj[key]);
        }
      }
      return obj;
    }
    
    const query = convertExtendedJSON(input);
    const result = await collection.find(query).toArray();
    
    

    This avoids evaluating arbitrary JS, and still allows typed fields like ObjectId, dates, etc.

  3. Optionally, you can validate the parsed object against a defined schema to avoid dangerous or malformed queries.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.