0

This question is 'similar' to this but I'm asking for alternative (if it exists).

I have create a db Nums with a collection numbers in the mongo shell.
Using mongoose as the ODM I want to access that collection and list the numbers.

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/Nums');
mongoose.model('numbers', new Schema({value: Number}));

mongoose.connection.on('open', function(ref) {
  console.log('Connected to mongo server.');
});

mongoose.connection.on('error', function(err) {
  console.log('Could not connect to mongo server!');
  console.log(err);
});

var nums = mongoose.model('numbers');
nums.find({}, function(err, data) {console.log(err, data, data.length);});

In order to access an already created database/collections do I always have to go through a mongoose.model and new Schema calls? Can this step be bypassed?

Even though this step has to be written once, it seems that if I have a very large schema this will be very tedious just to pull out a db/collection from mongo.

Is there a work around for this or this is the only path?

Community
  • 1
  • 1
user1460015
  • 1,973
  • 3
  • 27
  • 37

2 Answers2

0

If you want to use the Mongoose APIs to access a collection, you need to define a schema for it. If you don't want to define a schema for a collection, then you need to use the native driver or mongojs to access it.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I just tried this... it is possible simply to just call `mongoose.model('numbers', new Schema());` without specifying the schema layout. – user1460015 Nov 01 '12 at 21:16
  • @user1460015 You can use an empty schema, but then you lose a lot of the Mongoose functionality like the field type casting. I'm a little confused on why you'd be using Mongoose if you don't want those features. – JohnnyHK Nov 01 '12 at 21:28
  • It's just preference. If my schema looks like this http://www.reddit.com/r/funny/.json I'm going to have to leverage field type casting. It appears that I can type-cast certain fields but I don't have to do all of them. – user1460015 Nov 01 '12 at 21:34
0

After some experimenting the answer is "you have to specify the schema and model, but it's not that bad".

For instance, I could of done:

mongoose.connect('mongodb://localhost/Nums');
mongoose.model('numbers', new Schema());

but as @JohnnyHK mentions you miss out on the field type casting.

Also, suppose that you have a large schema, you can specify what you want to type-cast:

mongoose.connect('mongodb://localhost/Nums');
mongoose.model('numbers', new Schema({username: String, address: String}));

I only type-casted two fields.

user1460015
  • 1,973
  • 3
  • 27
  • 37