【问题标题】:How to find just one document with Restivus and Curl如何使用 Restivus 和 Curl 查找一个文档
【发布时间】:2015-11-28 21:38:37
【问题描述】:

我在使用 Restivus 时遇到了一个简单的初学者问题。

在我的 app.js 中我已经声明:

Players = new Mongo.Collection("players");

及以后:

if (Meteor.isServer) {
  // Global configuration
  Api = new Restivus({
    useDefaultAuth: true,
    prettyJson: true
  });

  // Generates: GET/POST on /api/v1/players, and GET/PUT/DELETE on     /api/v1/players/:id
  // for Meteor.users collection (works on any Mongo collection)
  Api.addCollection(Players);
  // That's it! Many more options are available if needed...
}

然后我启动“meteor mongo”

meteor:PRIMARY> db.players.insert({username:"Kalle", location:"Home"})
WriteResult({ "nInserted" : 1 })

meteor:PRIMARY> db.players.insert({username:"Pelle", location:"Away"})
WriteResult({ "nInserted" : 1 })

meteor:PRIMARY> db.players.find({});
{ "_id" : ObjectId("56598d83846a7b53e8a1176b"), "username" : "Kalle","location" : "Home" }
{ "_id" : ObjectId("56598d8c846a7b53e8a1176c"), "username" : "Pelle", "location" : "Away" }

当我使用 CURL 进行尝试时,我得到:

curl -X GET http://localhost:3000/api/players
{
  "status": "success",
  "data": [
    {
      "_id": {
        "_str": "56598d83846a7b53e8a1176b"
      },
      "username": "Kalle",
      "location": "Home"
    },
    {
      "_id": {
        "_str": "56598d8c846a7b53e8a1176c"
      },
      "username": "Pelle",
      "location": "Away"
    }
  ]

但是当我试图找到一个特定的文档时:

curl -X GET http://localhost:3000/api/players/56598d83846a7b53e8a1176b
{
  "status": "fail",
  "message": "Item not found"
}

为什么找不到文档,怎么回事:

"_id": {
    "_str": "56598d83846a7b53e8a1176b"
 }

【问题讨论】:

    标签: mongodb rest curl meteor


    【解决方案1】:

    由于meteor mongo 只是打开一个 MongoDB shell,因此创建文档时使用了 _id 的 ObjectId(这是 MongoDB id 的默认类型)。

    Meteor 默认为_ids 的随机字符串。因此,您示例中的 _id 不仅仅是您看到的字符串,而是包含它的整个 ObjectId。

    要使其工作,要么在 mongo shell 中显式设置 _id,要么(可能更好)使用 meteor shell 直接从 Meteor 服务器插入文档。

    【讨论】:

    • 太棒了!当我这样做时效果很好:“mongo shell”后跟“Players.insert({username:"Sven", location:"somewhere"});"之后 curl 命令localhost/api/players/:id 工作正常!
    • 你的意思是meteor shell
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多