2013-04-01 105 views
4

什麼是傳遞json文檔進行創建的正確方法?使用node.js在arangoDB中創建文檔

我有例子的工作和確定如下: /*創建集合*/

db.document.create({a:"test"},function(err,ret){ 
if(err) console.log("error(%s): ", err,ret); 
else console.log(util.inspect(ret)); 
}); 

一個新的文檔,但我如何在JSON的傳遞,因爲這不工作參數?

var json = '{a:"test"}'; 

db.document.create(json,function(err,ret){ 
if(err) console.log("error(%s): ", err,ret); 
else console.log(util.inspect(ret)); 

});

回答

2

看一看這個單元測試:https://github.com/kaerus/arango-client/blob/master/test/api/document.js

嘗試

var json = {"a":"test"}; 
+0

謝謝,我已經有了頭腦風暴!我使用流數據調用arango客戶端函數,這將成爲一個緩衝區,並且我將它翻譯爲一個字符串,根據您的意見,它顯然不被接受。我想我需要知道的是如何從字符串(或緩衝區)獲得您所建議的格式。 – user1305541

+0

JSON.parse(yourJsonString); ? – herrjeh42

4

以上從Kaerus庫 「創造」 的功能來看,在創建功能是:

"create": function() { 
    var collection = db.name, data = {}, options = "", callback, i = 0; 
    if(typeof arguments[i] === "boolean"){ 
    if(arguments[i++] === true) 
     options = "&createCollection=true"; 
    } 
    if(typeof arguments[i] === "string") collection = arguments[i++]; 
    if(typeof arguments[i] === "object") data = arguments[i++]; 
    if(typeof arguments[i] === "function") callback = arguments[i++]; 
    return X.post(xpath+collection+options,data,callback); 
}, 

所以您需要將它作爲JavaScript對象傳遞,即調用

JSON.parse('{"a":"test"}') 

的JSON表示形式轉換爲JavaScript對象或補丁Kaerus客戶 允許一個對象或字符串中的線

if(typeof arguments[i] === "object") data = arguments[i++]; 

(這可能會導致問題的可選參數)。

注意:任何情況下,「json」包含有效的JSON表示都很重要。

{ a: "Test" } 

是無效的,

{ "a": "Test" } 

是。

+0

我的數據在流中,所以它是一個緩衝區。我將它轉換爲一個字符串,然後做了一個JSON.parse。這不起作用,我回到'404'的迴應。 JSON是有效的(在這裏測試的緩衝區上的'console.log'的輸出:http://jsonlint.com/)。如果我直接傳入數據,它可以正常工作......非常令人困惑...... – user1305541

+0

好吧,那很奇怪。 404並不意味着「腐敗的JSON」,而是「收集未找到」。你可以嘗試以下方法:db.document.create(「COLLECTIONNAME」,json,function(err,ret)如果(err)console.log(「error(%s):」,err,ret); else console.log(util.inspect(ret));其中COLLECTIONNAME是你正在使用的集合的名稱? – fceller

+0

我試過了,404錯誤已修復。它創建一個文檔,但沒有任何傳入的json數據,我只是填充了_id,_key和__rev字段,'create'的回調函數沒有被調用,所以2個控制檯行沒有輸出。 – user1305541