既然您似乎熟悉ORM模式,我會推薦使用"mongoose" module。雖然我猜想你會通過NodeJS和Mongo有一個很大的學習曲線來製作一個可靠的應用程序。
這裏的工作的例子,讓你雖然起步:在「mytest.csv」
#! /usr/bin/node
var mongoose = require('mongoose');
mongoose.connect('localhost', 'test');
var fs = require('fs');
var lineList = fs.readFileSync('mytest.csv').toString().split('\n');
lineList.shift(); // Shift the headings off the list of records.
var schemaKeyList = ['RepName', 'OppID', 'OppName', 'PriorAmount', 'Amount'];
var RepOppSchema = new mongoose.Schema({
RepName: String,
OppID: String,
OppName: String,
PriorAmount: Number,
Amount: Number
});
var RepOppDoc = mongoose.model('RepOpp', RepOppSchema);
function queryAllEntries() {
RepOppDoc.aggregate(
{$group: {_id: '$RepName', oppArray: {$push: {
OppID: '$OppID',
OppName: '$OppName',
PriorAmount: '$PriorAmount',
Amount: '$Amount'
}}
}}, function(err, qDocList) {
console.log(util.inspect(qDocList, false, 10));
process.exit(0);
});
}
// Recursively go through list adding documents.
// (This will overload the stack when lots of entries
// are inserted. In practice I make heavy use the NodeJS
// "async" module to avoid such situations.)
function createDocRecurse (err) {
if (err) {
console.log(err);
process.exit(1);
}
if (lineList.length) {
var line = lineList.shift();
var doc = new RepOppDoc();
line.split(',').forEach(function (entry, i) {
doc[schemaKeyList[i]] = entry;
});
doc.save(createDocRecurse);
} else {
// After the last entry query to show the result.
queryAllEntries();
}
}
createDocRecurse(null);
您的數據:
Rep Name,Opp ID,Opp Name,Prior Amount,Amount
Rep 1,1234561,Opp 1,10000,8000
Rep 1,1234562,Opp 2,15000,9000
Rep 2,1234563,Opp 3,20000,10000
Rep 1,1234564,Opp 4,25000,11000
Rep 2,1234565,Opp 5,30000,12000
是否有可能建立一個代表模型,並有進口過程分開?最初,我有一個rep的模型設置,然後我正在瀏覽控制檯,使用mongoimport將csv數據導入數據庫,並使用頭文件作爲變量名稱來代表模型。我覺得你所提供的絕對是我想要走的方向。 – petey
回覆:是否可以爲代表設置模型並使導入過程分離? - 當然。多個進程可以連接到同一個數據庫。雖然對於貓鼬模型模式定義需要在所有的過程中。 – mjhm
我能夠測試出來,它效果很好!我設法設置了模型,並從一個單獨的頁面導入過程,允許用戶單擊按鈕導入數據。我現在唯一遇到的問題是Nodemon(我正在使用Nodemon來幫助開發過程)不希望在數據導入後重新啓動。我確定這可能是我在代碼中缺少的東西。有什麼想法可能是什麼? – petey