简体   繁体   中英

Meteor: execute meteor mongo within app and get collection all names

I am trying to connect to the local mongodb server within the meteor app so that I can get the list of all collections within a server-side function.

The following command variable does execute and returns

/Users/myProject/.meteor/local/build/programs/server

Now I would like to execute the commandWanted variable, aiming to retrieve a list of all mongo db collections.

server.js

var Future = Meteor.npmRequire("fibers/future");
var exec = Npm.require('child_process').exec;


function shell() {
    var future = new Future();
    var command = "pwd";
    var commandWanted = "meteor mongo" + "db.getCollectionNames()";
    exec(commandWanted, function(error,stdout,stderr){
            if (error) {
                    console.log(error);
                    throw new Meteor.Error(500, "failed");
            }
            console.log(stdout.toString());
            future.return(stdout.toString());
    });
    return future.wait();
}


shell();

Use the RemoteCollectionDriver to access a preexisting MongoDB Collections

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
db.collectionNames(function(err, collections) {
    if (err) throw err;
    console.log(collections);
});

// for commands not natively supported by the driver - http://docs.mongodb.org/manual/reference/command/
db.command({profile: 1}, function(error, result) {
    if (error) throw error;
    if (result.errmsg)
        console.error('Error calling native command:', result.errmsg);
    else
        console.log(result);
});

To implement this server side, you could follow this asynchronous pattern:

var shell = function () {
    var Future = Npm.require('fibers/future'),
        future = new Future(),
        db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    db.collectionNames( 
        function(error, results) {
            if (err) throw new Meteor.Error(500, "failed");
            future.return(results);
        }
    );
    return future.wait();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM