2017-02-23 3 views
0

mongo 컬렉션을 url 매개 변수로 전달하고 레코드를 검색하는 액션을 sails.js에 만들었습니다.sails.js와 waterline을 사용하여 mongodb의 레코드를 동적으로 검색합니다.

'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(); 
    }); 
} 

}};

URL은 http://localhost:1337/forms/formRecords?collection=quotes과 같으며 json 개체의 레코드를 반환합니다. 내가 그렇게 http://localhost:1337/forms/formRecords?collection=users 항해 오류 밖으로 형식 오류와 같은 다른 컬렉션 다시 같은 동작을 사용하려고하면 : 나는 orm.teardown() 함수를 추가하는 시도 정의되지 않은의 특성 '컬렉션'을 읽을 수 있지만 그것은 빈을 반환 할 수 없습니다 보기 (정의되지 않음). 수류를 다시 초기화하고 새 컬렉션을로드하는 방법에 대한 아이디어가 있습니까?

+0

이 컬렉션은 Sails 앱에서 모델로 정의 된 요청 매개 변수입니까? – Sangharsh

+0

사용자는 mongodb에 새 콜렉션을 생성하는 자체 양식을 작성할 수있는 권한을 부여 했으므로 모델이 생성되지 않습니다. 내가 뭘 하려는지는이 코드가 수행하는 지정된 컬렉션'req.param ('collection')에 저장된 레코드를 검색하는 것이지만 새로운 콜렉션을 요청하자마자 ** TypeError : 속성 'collections을 읽을 수 없다. '정의되지 않음 **. 워터 라인이 이미 초기화 되었기 때문에 워터 라인을 다시 초기화하고 다른 콜렉션을 요청할 수있는 방법이 필요하다고 생각합니다. – mblais29

+0

['.native()'] (http://sailsjs.com/documentation/reference/waterline-orm/models/native)를 사용하여 작동합니까? 질문? – Sangharsh

답변

1

나는 그것을 알아낼 수 있었다. 내가 좋아하는 액션이 ​​너무

localhost:1337/forms/formRecords?collection=collectionName

그런 다음 내 formRecords에 작업은 내가 인수 req.param ('수집')를 전달 그래서

'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(); 
     }); 
    }); 
} 

처럼 보이는 전화가 모든 레코드를 검색 mongo 데이터베이스의 모든 콜렉션에 대해.