2017-02-23 67 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

谢谢!这工作! –