0
我如何使用Node.js到:編輯內容導入到MongoDB的
- 查詢外部API。
- 將JSON結果保存到文件。
- 將查詢結果導入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
}
}
]
爲什麼不插入'response [「data」]'而不是'response'? –