mblais29
mblais29

Reputation: 349

Dynamically retrieve records in mongodb using sails.js and waterline

I have created an action in sails.js that passes in a mongo collection as a url parameter and retrieves the records.

'formRecords': function(req, res, next){

    var orm = new Waterline();

    var config = {
        // Setup Adapters
        // Creates named adapters that have been required
        adapters: {
            'default': 'mongo',
            mongo: require('sails-mongo')
        },
                         // Build Connections Config
        // Setup connections using the named adapter configs
        connections: {
            'default': {
                adapter: 'mongo',
                url: 'mongodb://localhost:27017/db'
            }
        }
    };


    var record = Waterline.Collection.extend({
        identity: req.param('collection'),
        connection: 'default'
    });

    orm.loadCollection(record);

    orm.initialize(config, function(err, models) {
        var mongoCollection = models.collections[req.param('collection')];

        //May need to create a whole new page to re-direct to for form records so we can orm.teardown() like in the create action
        mongoCollection.find()
        .exec(function(err, result){
            console.log(result);
            res.json(result);
            /*res.view('forms/formRecords', {
              data: result
            });*/
        });
     //Must have orm.teardown() to close the connection then when adding a new collection I do not get the Connection is already registered error.
        //orm.teardown();
    });
}

};

The url looks like http://localhost:1337/forms/formRecords?collection=quotes it returns the records in a json object. If I try to use the same action again with a different collection like so http://localhost:1337/forms/formRecords?collection=users Sails errors out TypeError: Cannot read property 'collections' of undefined I tried adding the orm.teardown() function but it returns a blank view (undefined). Any idea how to to re-initialize waterline with and load a new collection?

Upvotes: 0

Views: 496

Answers (1)

mblais29
mblais29

Reputation: 349

I managed to figure it out. I call the action like so

localhost:1337/forms/formRecords?collection=collectionName

Then in my formRecords action looks like so

'formRecords': function(req, res, cb){
    var findRecords = function(db, callback) {
      // Get the collection records
      var collection = db.collection(req.param('collection'));
      // Find some records
      collection.find({}).toArray(function(err, records) {
        assert.equal(err, null);

        //Returns the records found for the specified collection
        res.json(records);
        callback(records);
      });
    };
    var MongoClient = require('mongodb').MongoClient
        , assert = require('assert');

    // Connection URL
    var url = 'mongodb://localhost:27017/databaseName';
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, db) {
      assert.equal(null, err);
      console.log("Connected correctly to server");
        findRecords(db, function() {
          db.close();
        });
    });
}

I pass in the argument req.param('collection') and it retrieves all records for any collection in the mongo database.

Upvotes: 1

Related Questions