0

I need to send the following example MongoDB query from a React.JS frontend app to a backend Node.js API via URL request params:

{
  _id: ObjectId('507f1f77bcf86cd799439011'),
  name: {
    $in: ['foo', 'bar']
  }
}

However, ObjectId is a function and cannot be serialized to JSON. So, I tried this BSON form as proposed in https://stackoverflow.com/a/34486720/6039697:

{
  "_id": {
    "$oid": "507f1f77bcf86cd799439011"
  },
  "name": {
    "$in": ["foo", "bar"]
  }
}

But MongoDB show this error

{
    "message" : "unknown operator: $oid",
    "ok" : 0,
    "code" : NumberInt(2),
    "codeName" : "BadValue",
    "name" : "MongoError"
}

I Know I could check for _ids and parse in the API, but I would like to make this transparent and automatic. Does anyone have an idea on how can I get this working?

8
  • 1
    It sounds like you want to to backend stuff in the frontend. Are you using mongoose? What you should do is issue a GET on something like myapi.com/whatever/507f1f77bcf86cd799439011. On you backend, you can simply get that id from the parameters object and pass it to mongoose. Commented Jun 30, 2020 at 14:51
  • @ffritz yeah, I wanto to make queries in general from the frontend. I'm using mongoose. The route id you propose are already in use for patch/delete request mappings, but I need to make queries with other fields other than _id, so, do it in route ids will not work Commented Jun 30, 2020 at 14:55
  • I'll insert the general queries part in question to make it more clear Commented Jun 30, 2020 at 14:57
  • 1
    It sounds like you almost want a "catch all" route which freely parses mongoDB queries from your frontend. That is a very bad idea, as it opens very critical attack vectors. Commented Jun 30, 2020 at 15:01
  • Yes! You are totally right. But I think if I encrypt this query it will be more safe to attacks. What do you think? Commented Jun 30, 2020 at 15:09

1 Answer 1

0

I found a solution to my question. This package solved my problem https://www.npmjs.com/package/bson

const { EJSON } = require('bson');

const mongoDBQuery = EJSON.parse(JSON.stringify({
  "_id": {
    "$oid": "507f1f77bcf86cd799439011"
  },
  "name": {
    "$in": ["foo", "bar"]
  }
}), { relaxed: true });

console.log(mongoDBQuery);
Sign up to request clarification or add additional context in comments.

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.