Christian Buchwald
Christian Buchwald

Reputation: 570

Unable to search for ObjectID in MongoDB stitch service

I've been trying for hours to make this simple query work, but somehow it doesn't. I've created a HTTP service in MongoDB Stitch and I call the service with an ID like this

https://stitchurl.myservice?ID=blablabla

inside the service I want to disable the account with ID x so I tried to call it like this:

exports = function(payload) {

    var queryArg = payload.query || '';
    var ID = queryArg.ID || '';
    if(ID !== "")
    {
        const mongodb = context.services.get("mongodb-atlas");
        const mycollection = mongodb.db("myDB").collection("myCollection");
        var oID = new BSON.ObjectId(ID);
        return mycollection.updateOne({oID}, {$set:{isdisabled: true}});
    }
}

no matter if I query:

{ID}
{oID}
{_id:ID}
{_id:oID}
...

I always receive 0 results, but when I'm in the MongoDB Atlas collections I can query for

{_id:ObjectId("myID")}

and receive the proper result. There's no problem with rules or rights, because if I run

return mycollection.findOne({})

I get a proper hit.

Any ideas what I'm doing wrong?

Regards Christian

Upvotes: 3

Views: 998

Answers (1)

vbuser2004
vbuser2004

Reputation: 1042

Had a similar issue that took me a while to figure out. The issue is (possibly) due to the 'Rules' associated with this collection. Go the the 'Rules' menu item within your Stitch app, and then select the 'schema' tab next to permissions. Here you will see something like this:

{
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "user_id": {
      "bsonType": "string"
    }
  }
}

In the case above, the _id field is an objectId, but the user_id field is a string. The schema has to match what you are searching. Hope this helps!

Upvotes: 1

Related Questions