0

我正在写 Mongodb Stitch,函数。

奇怪的是,在 Mongodb Stitch 函数客户端中编写它,它必须做 BSON.ObjectId

    const games = mongodb.collection("games");
    const gameId = "5cb9404ffc6da85909eb561c";
    const objectId = BSON.ObjectId(gameId);
    const query = { "_id" : objectId };
    return games.findOne(query);

但是,当我使用我的应用程序传递arg给函数时,它会抱怨 [StitchServiceError: Error: ObjectId in must be a single string of 12 bytes or a string of 24 hex characters]

我必须将其恢复为

    const gameId = "5cb9404ffc6da85909eb561c";
    const query = { "_id" : gameId };
    return games.findOne(query);

null如果我在 MongoDB Stitch 函数客户端中对其进行测试,这将返回。

为什么 MongoDB 以这种方式设计?

4

2 回答 2

0

要使应用程序正常工作,您只需要传递 id 字符串。

const gameId = "5cb9404ffc6da85909eb561c";
const query = { "_id" : gameId };
return games.findOne(query);
于 2019-04-20T06:44:45.240 回答
0

这对我有用:

    exports = function(payload, response) {
      const mongodb = context.services.get("mongodb-atlas");
      const collection = mongodb.db("mydatabase").collection("mycollection");
      // const id = "5f2b7706fae92314e01a2c3c";
      // let cursor = collection.findOne({_id: BSON.ObjectId(id)});
      let cursor = collection.findOne({_id: BSON.ObjectId(payload.query.id)});
      cursor.then(function(result){
        response.setStatusCode(200);
        response.setHeader(
          "Content-Type",
          "application/json"
        );
        response.setBody(JSON.stringify(result));
      });
    };

然后进行测试:

https://yourwebhookurl?id=5f2b7706fae92314e01a2c3c

另见:https ://intercom.help/mongodb-atlas/en/articles/1566512-how-do-i-work-with-objectid-in-stitch

于 2020-08-07T19:34:35.747 回答