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?
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:
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:
I only type-casted two fields.