新手不能得到JSON

时间:2014-02-24 22:02:09

标签: mongodb livecode

在LiveCode中我有一个连接到localhost MongoDB的堆栈,堆栈有一个带有鼠标处理程序的按钮和来自MergJSON的函数JSONToArray以及两个字段:“A”以“按原样”和字段B“接收服务器答案”接收解码的JSON。

这是按钮的脚本:

on mouseup
  set the hideConsoleWindows to true
  put shell("C:\\mongodb\bin\mongo.exe --eval" && quote & \ 
    "printjson(db.test.findOne())" & quote) into pJSON
  put pJSON into fld "a"
  put JSONToArray(pJSON) into tArray
  put tArray["a"] into fld "B"
end mouseup

mouseup后fld“A”的内容为:

MongoDB shell version: 2.2.7
connecting to: test
{ "_id" : ObjectId("52e3f87c8da8b1efb07004c9"), "a" : 1 }

脚本失败,出现以下LiveCode错误:

        executing at 8:58:32 PM
Type    could not decode JSON: invalid token near 'MongoDB'
Object  Completo
Line    repeat for each line tKey in mergJSONDecode(pJSON,"tArray")
Hint    could not decode JSON: invalid token near 'MongoDB'

如果我将脚本更改为:

on mouseup
  put shell("C:\\mongodb\bin\mongo.exe --eval" && quote & "printjson(db.test.find())" & quote) into pJSON
  put pJSON into fld "A"
end mouseup

字段“A”得到这个:

MongoDB shell version: 2.2.7
connecting to: test
{
    _"_mongo" : connection to 127.0.0.1,
    _"_db" : test,
    _"_collection" : test.test
    _"_ns" : "test.test",
    _"_query" : {
    __
_},
    _"_fields" : null,
    _"_limit" : 0,
    _"_skip" : 0,
    _"_batchSize" : 0,
    _"_options" : 0,
    _"_cursor" : null,
    _"_numReturned" : 0,
    _"_special" : false,
    _"help" : function () {
    print("find() modifiers");
    ...
    ...
    ...
}

我缩短了实际字段“A”的内容,它有很多文字。

你能指导我吗?我做错了什么?为什么我没有获得JSON。我使用在线服务查找{ "_id" : ObjectId("52e3f87c8da8b1efb07004c9"), "a" : 1 }检查了它不是有效的JSON。

2 个答案:

答案 0 :(得分:0)

尝试仅使用{until}中的字符串,而不使用前面的行。

on mouseUp
  set the hideConsoleWindows to true
  put shell("C:\mongodb\bin\mongo.exe --eval" && \
    quote & "printjson(db.test.findOne())" & quote) into pJSON
  put pJSON into fld "a"
  put JSONToArray(line 3 to -1 of pJSON) into tArray // <-- this line changed
  put tArray["a"] into fld "B"
end mouseUp

答案 1 :(得分:-4)

回答“我做错了什么?”当你在集合上调用.find()时,首先需要了解自己在做什么。

现在,由于该链接中的文档会告诉您(位于页面顶部)您 从此调用中返回结果,但事实上您正在返回一个cursor。现在你可以看到,当调用它时,shell就会出现一系列文件。

但发生这种情况的唯一原因是shell(以交互形式)充当REPL并且评估您的语句以便打印输出。因此,交互式 shell正在评估您的cursor并多次调用.next()方法。在shell中工作时,这只是 一个便利功能。

为了按计划以编程方式获取结果,您需要使用此cursor 执行某些操作来实际查看结果。现在你可以创建一个循环,你在每次调用.next()的结果上迭代,但为了你的目的,.toArray()方法就足够了。< / p>

因此,在略微扩展的方式中,为了清晰定义,您将拥有这样的脚本表单:

var cursor = db.test.find();

var results = cursor.toArray();

printjson( results );

或者使用方法链接作为一般 one liner

printjson( db.test.find().toArray() )

这将发出您需要的文档的JSON 数组

或者,您可以使用.findOne()方法,它只返回一个文档,您可以将其传递给printjson()函数。