baugarten / node-restful

A library for quickly providing a REST API with express or connect
http://www.baugarten.me/node-restful/
1.31k stars 249 forks source link

Separate connection compatibility #97

Open puradawid opened 9 years ago

puradawid commented 9 years ago

Is there any chance to node-restful will work with separated mongoose collection? I mean is there possibility to:

var restful = require('node-restful')
var connection = mongoose.createConnection();
var restfulModel = restful.model(someName, someSchema, connection);

I can't find feature like that, anyway that would be useful.

d3dc commented 9 years ago

This is definitely doable, but it seems like you have to use non-public APIs.

The connection.model() function creates a mongoose model that belongs to it and but does not cache it on the mongoose object. (otherwise we could just look it up with restful.model(someName) after using connection.model(someName,someSchema))


mongoose/lib/connection.js:

Connection.prototype.model = function (name, schema, collection) {
...
var opts = { cache: false, connection: this };
...
  if (schema instanceof Schema) {
      // compile a model
      model = this.base.model(name, schema, collection, opts);
...

this.base.model is the same function restful.model() just passes all its arguments to: mongoose.model().

node-restful/lib/model.js:

node-restful/lib/model.js
function model() {
  var result = mongoose.model.apply(mongoose, arguments),
  ...
}

So you can actually do:

var restfulModel = restful.model('MyModel, mySchema, 'MyModels', { connection: myConnection });

Obviously this is more of a hack. You will always have to pass the name of the collection, and the function signature may change in future versions of Mongoose.