2017-02-23 30 views
0

我如何使用Node.js到:編輯內容導入到MongoDB的

  1. 查詢外部API。
  2. 將JSON結果保存到文件。
  3. 將查詢結果導入MongoDB。代碼

例子:

//Query the API and save file 

var file = '../data/employees.json'; 
tl.employees.all(function(response) { 
fs.writeFile(file, JSON.stringify(response, function(key, value) { 
    var result = value; 
    return result; 
}, 3, 'utf8')); 

//Inserts API response above to MongoDB 

var insertDocument = function(db, callback) { 
    db.collection('employees').insert(response, function(err, result) { 
     assert.equal(err, null); 
     console.log("Step 2: Inserted Employees"); 
     callback(); 
    }); 
}; 

這是所有工作的罰款,我得到了以下JSON保存到文件,並導入到MongoDB的:

{ 
"data": [ 
{ 
"full name": "Keith Richards", 
"age": 21, 
"userName": "[email protected]", 
"employeeDetails": { 
    "id": 102522 
} 
}, 
{ 
"full name": "Jim Morrison", 
"age": 27, 
"userName": "[email protected]", 
"employeeDetails": { 
    "id": 135522 
} 
} 
] 
} 

的問題是,由於「數據」部分,這會作爲1個對象導入到MongoDB中。

像這樣:

{ 
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"), 
"data" : [ 
    { // contents as shown in JSON above .. 

這使得聚集和配套真的很難(或不可能)。

是否有剝離出的「數據」部分,只需要導入它的內容的一種方式,所以每個「員工」將成爲它自己的對象是這樣的:

[ 
{ 
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"), 
"full name": "Keith Richards", 
"age": 21, 
"userName": "[email protected]", 
"employeeDetails": { 
    "id": 102522 
} 
}, 
{ 
"_id" : ObjectId("234332c10d7a5005fc8370"), 
"full name": "Jim Morrison", 
"age": 27, 
"userName": "[email protected]", 
"employeeDetails": { 
    "id": 135522 
} 
} 
] 
+1

爲什麼不插入'response [「data」]'而不是'response'? –

回答

1

這樣你就可以解析JSON然後將其發送到文件。得到結果後,使用parseJSON(data)來檢查它是否包含「data」字段。如果是的話,獲取數組中的數組並將其存儲到文件中。 基本上,我已經更多地解釋了@Bertrand所說的話。 希望這有助於。

+0

謝謝!這工作! –