Mongoose read-only without schema

I use Mongoose in my node.js application to simulate two collections in the database that it will read and write. There are two more collections that will be read only from my application (the model for these collections is supported in another application that will write for them).

If I need to access two read-only collections using mongoose, then I will also have to maintain the schema in this application. I would prefer not to do this, as the scheme will be supported twice and may lead to inconsistencies later.

Mongoose default connection can be created

Mongoose.connect(dbPath) 

Given dbPath (e.g. mongodb://localhost/dbname ), how can I use the default Mongoose connection to read from a collection whose schema / model is not supported by my application? Or will I have to use my own MongoDB driver for the same?

+5
source share
1 answer

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

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

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

Or, to improve performance, include lean() in the query chain if you don't need any model instance functionality:

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

If you are not using lean() , you need to access the properties of the document using the get method; eg:

 doc.get('name') // instead of doc.name 
+9
source

Source: https://habr.com/ru/post/1213812/


All Articles