2016-01-22 53 views
0

我最近升級到5.4的節點和MongoDB 2.1.4驅動程序的節點,我有以下問題:節點/ MongoDB的JSON空數組錯誤

我有一個包含這樣的事情叫做buildings.json文件:

{ 
    "military_base": { 
     "type": "military", 
     "level": 0, 
     "maxLevel": 25, 
     "upgrade": true, 
     "targetEnvironment": [], 
     "timeUntilBuilt": 0, 
     "costCoef": 0.4, 
     "requiredResearches": [ 
      "foo#4", 
      "bar#1" 
     ], 
     "requiredResources": [ 
      "cash", 
      "metal", 
      "palladium" 
     ], 
     "inProgress": 0, 
     "queue": [] 
    }, 
    "aqua_center": { 
     "type": "industrial", 
     "level": 0, 
     "maxLevel": 25, 
     "upgrade": true, 
     "targetEnvironment": [ 
      "ocean", 
      "snowy" 
     ], 
     "timeUntilBuilt": 0, 
     "costCoef": 0.7, 
     "requiredResearches": [ 
      "lorem#10", 
      "ipsum#3" 
     ], 
     "requiredResources": [ 
      "cash", 
      "cristal" 
     ], 
     "inProgress": 0, 
     "queue": [] 
    } 
} 

現在,我想這個文件插入到數據庫蒙哥:

let buildings = require("buildings"); 
... 
collection.insertOne({ foo: buildings }, callback); 

如果第一"targetEnvironment"數組是空的,什麼都沒有插入,回調不是C alled,並沒有錯誤。但如果它被填充,一切都很好,回調被稱爲和文檔被正確插入... 我必須承認,我不知道如果問題是與Node或MongoDb驅動程序有關...

有人能幫助我嗎 ?

+0

在升級之前,是否也做了同樣的插入工作? – metame

+0

是的,我使用了Nodejs v0.12和MongoDb Driver v1.4。 – Paradox

+0

你可以記錄錯誤或打開你的'mongod'的調試日誌嗎? – metame

回答

0

哦...因爲我有一個64位的Windows,我安裝了64位nodejs版本,問題來自於這裏... 32位,沒有錯誤! :o

0
#!/usr/bin/env node 

const mongodb = require("mongodb"); 
const MongoClient = mongodb.MongoClient; 
const ObjectID = mongodb.ObjectID; 

MongoClient.connect("mongodb://127.0.0.1:27017/test", function(err, db) { 
    if (err) { 
     throw err; 
    } 

    var collection = db.collection("test-insert"); 
    collection.insertOne(test, (err, obj) => { 
     if (err) { 
      throw err; 
     } 

     console.log(obj.insertedId); 

     db.close(); 
    }); 
}); 

var test = { 
    "military_base": { 
     "type": "military", 
     "level": 0, 
     "maxLevel": 25, 
     "upgrade": true, 
     "targetEnvironment": [], 
     "timeUntilBuilt": 0, 
     "costCoef": 0.4, 
     "requiredResearches": ["foo#4", "bar#1"], 
     "requiredResources" : ["cash", "metal", "palladium"], 
     "inProgress": 0, 
     "queue": [] 
    }, 
    "aqua_center": { 
     "type": "industrial", 
     "level": 0, 
     "maxLevel": 25, 
     "upgrade": true, 
     "targetEnvironment": ["ocean", "snowy"], 
     "timeUntilBuilt": 0, 
     "costCoef": 7, 
     "requiredResearches": ["lorem#10", "ipsum#3"], 
     "requiredResources" : ["cash", "cristal"], 
     "inProgress": 0, 
     "queue": [] 
    } 
}; 

如果我嘗試插入此文檔,它將不會被插入,因爲第一個costCoef屬性是一個浮點數。如果它像時間戳那樣大,它也會失敗。

+0

哦,你是說你插入一個浮動數字會失敗嗎?這絕對不應該發生。絕對看起來像一個可能的錯誤。 – metame

+0

圍繞它的一種方法是在插入之前將你的浮動轉換爲字符串,然後在檢索時將它們重新轉換爲數字/浮動(如果你必須對它們做些什麼) – metame

+0

是的,這是問題所在。 我有很多代碼使用時間戳和浮點數與數據庫,我不想重寫10.000行...... :( – Paradox