ZeMoon ZeMoon - 1 year ago 132
Node.js Question

Mongoose read-only without schema

I am using Mongoose in my node.js app to model two collections in the database, which it will read and write. There are two more collections which are going to be read only from my app (the model for these collections is being maintained in another app, which will write to them).

If I need to access the two read-only collections using mongoose, then I will have to maintain a schema within this app as well. I would rather not do this as the schema will be maintained twice and could lead to inconsistency later on.

The default connection in Mongoose can be created by


Given a dbPath (e.g.
), how can I use the Mongoose default connection to read from a collection whose schema/model is not being maintained by my app? Or will I have to use the native MongoDB driver for the same?

Answer Source

If you're just using Mongoose to read from a collection, you can leave the schema definition empty.

So if you had a read-only collection named test, something like this will work:

var Test = mongoose.model('Test', new Schema(), 'test');
Test.findOne({name: 'John'}, function(err, doc) { ... });

Or for better performance, include lean() in your query chain if you don't need any of the model instance functionality:

Test.findOne({name: 'John'}).lean().exec(function(err, doc) { ... });

If you don't use lean() you need to access the properties of the doc using the get method; for example:

doc.get('name') // instead of doc.name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download