由于您似乎熟悉 ORM 模式,我建议您使用“mongoose”模块。虽然我猜想你会在 NodeJS 和 Mongo 方面有很长的学习曲线来制作一个可靠的应用程序。
这是一个可以帮助您入门的工作示例:
#! /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);
您在“mytest.csv”中的数据:
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