如何在作业完成后用mongoose关闭活动的MongoDB连接?

时间:2017-03-07 11:15:14

标签: mongodb mongoose disconnect database

如您所见,我正在连接数据库,从目录中读取多个JSON文件,并在mongoose的帮助下将它们导入MongoDB服务器。 完成这项工作后,我想关闭连接并打印出“工作完成”

我该怎么做?

var mongoose            = require('mongoose'),
    _                   = require('lodash'),
    fs                  = require('fs'),
    path                = require('path');

mongoose.Promise   = require('bluebird'),

mongoose.connect('mongodb://localhost/eclass');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
    // we're connected!
    // create db schema
    var EclassSchema = new mongoose.Schema({
        xsi: {
            xsitype: 'string',
            id: 'string'
        },
        date_of_original_definition: 'string',
        date_of_current_version: 'string',
        date_of_current_revision: 'string',
        revision: 'string',
        status: 'string',
        source_language: {
            country_code: 'string',
            language_code: 'string'
        },
        preferred_name: 'string',
        definition: 'string',
        its_superclass: 'string',
        hierarchical_position: 'string',
        //keywords: 'string'
    });
    // Create model
    var Eclass = mongoose.model('Eclass', EclassSchema);

    const pjsons = path.join(__dirname, '/../', 'file-operations', 'json-files');
    console.log(pjsons);

    function readFiles(pjsons, onError) {
        fs.readdir(pjsons, function(err, filenames) {
            if(err) {
                onError(err);
                return;
            }

            filenames.forEach(function(filename) {
                fs.readFile(pjsons + '/' + filename, 'utf-8', function(err, data) {
                    if(err) {
                        onError(err);
                        return;
                    }
                    data = JSON.parse(data);
                    // Digging down into the json code
                    const ontomlOntoml = data['dic:eclass_dictionary']['ontoml:ontoml'];
                    const onto = _.first(ontomlOntoml);
                    const dictionary = onto['dictionary'];
                    const contClasses = _.first(dictionary);
                    const containedClasses = contClasses['contained_classes'];
                    const ontClass = _.first(containedClasses);
                    const ontomlClass = _.find(ontClass);      

                    //Arrays
                    const xsiArray = _.map(ontomlClass, '$');
                    const date_of_original_definitionArray = _.map(ontomlClass, 'date_of_original_definition');
                    const date_of_current_versionArray = _.map(ontomlClass, 'date_of_current_version');
                    const date_of_current_revisionArray = _.map(ontomlClass, 'date_of_current_revision');
                    const revisionArray = _.map(ontomlClass, 'revision');
                    const statusArray = _.map(ontomlClass, 'status');
                    const sourceLanguageArray = _.map(ontomlClass, 'source_language');
                    const preferredNameArray = _.map(ontomlClass, 'preferred_name');
                    const definitionArray = _.map(ontomlClass, 'definition');
                    const itsSuperclassArray = _.map(ontomlClass, 'its_superclass');
                    const hierarchical_positionArray = _.map(ontomlClass, 'hierarchical_position');
                    //const keywordsArray = _.map(ontomlClass, 'keywords');

                    // Looping and storing the data into mongodb
                    //for (var i = 0; i < hierarchical_positionArray.length; i++) {
                    for (var i = 0; i < 2; i++) {
                        //console.log(hierarchical_positionArray[i]);
                        var newEclass = new Eclass();
                        newEclass.xsi.xsitype = xsiArray[i]['xsi:type'];
                        newEclass.xsi.id = xsiArray[i]['id'];
                        newEclass.date_of_original_definition = date_of_original_definitionArray[i];
                        newEclass.date_of_current_version = date_of_current_versionArray[i];
                        newEclass.date_of_current_revision = date_of_current_revisionArray[i];
                        newEclass.revision = revisionArray[i];
                        newEclass.status = statusArray[i];
                        newEclass.source_language.country_code = sourceLanguageArray[i][0].$.country_code;
                        newEclass.source_language.language_code = sourceLanguageArray[i][0].$.language_code;
                        newEclass.preferred_name = preferredNameArray[i][0].label[0]._;
                        newEclass.definition = definitionArray[i][0].text[0]._;
                        newEclass.its_superclass = itsSuperclassArray[i][0].$.class_ref;
                        newEclass.hierarchical_position = hierarchical_positionArray[i];
                        //newEclass.keywords = keywordsArray[i][0].label[0]._;
                        newEclass.save(function (err) {});
                    }
                });
            });
        });
    }
    readFiles(pjsons);
});

2 个答案:

答案 0 :(得分:0)

mongoose.disconnect()关闭所有已打开的连接。更多 http://mongoosejs.com/docs/api.html#index_Mongoose-disconnect

答案 1 :(得分:0)

我解决了这个问题:

        newEclass.save()
        .then(function() {
            mongoose.disconnect();
        })
        .catch(function(err) {
            console.log('There was an error', err);
        });

...

const mongoose  = require('mongoose'),
    parse       = require('csv-parse'),
    path        = require('path'),
    fs          = require('fs');

mongoose.Promise = require('bluebird');

mongoose.connect('mongodb://localhost/eclassCSV');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
    // we're connected!
    // create db schema
    const EclassSchema = new mongoose.Schema({
        codedName: { type: String, min: 10, max: 10 },
        preferredName: { type: String, max: 80 },
        definition: { type: String, max: 1023 },
        level: { type: String, min: 1, max: 1 },
        mkSubclass: { type: String, min: 1, max: 1 },
        mkKeyword: { type: String, min: 1, max: 1 }
    });

    // Create MongoDB model with mongoose
    const Eclass = mongoose.model('Eclass', EclassSchema);

    const p = path.join(__dirname, '/../', 'file-operations', 'csv-files');
    //console.log(p);

    const parser = parse({delimiter: ';'}, function(err, data){
        //console.log(data);
        //const supplier = data[0][0];
        const codedName = data.map((item,i) => data[i][6]);
        const preferredName = data.map((item,i) => data[i][7]);
        const definition = data.map((item,i) => data[i][8]);
        const level = data.map((item,i) => data[i][13]);
        const mkSubclass = data.map((item,i) => data[i][14]);
        const mkKeyword = data.map((item,i) => data[i][15]);

        // Looping and storing the data into mongodb
        //console.log(ontomlClass.length);
        for (let i = 0; i < data.length; i++) {
            //console.log(hierarchical_positionArray[i]);
            const newEclass = new Eclass();
            newEclass.codedName = codedName[i];
            newEclass.preferredName = preferredName[i];
            newEclass.definition = definition[i];
            newEclass.level = level[i];
            newEclass.mkSubclass = mkSubclass[i];
            newEclass.mkKeyword = mkKeyword[i];
            newEclass.save()
            .then(function() {
                mongoose.disconnect();
            })
            .catch(function(err) {
                console.log('There was an error', err);
            });
        }
    });
    fs.createReadStream(p + '/One-eClass-10_0_CC_en.csv').pipe(parser);
});