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
Mongoose.connect(dbPath)
Given a dbPath (e.g. mongodb://localhost/dbname
), 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?
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
Yes, of course, drivers provide many advantages to make our lives easy. But to keep things simple and lightweight we can use only MongoDB for CRUD operation without a mongoose. What about validation? Don't worry, packages like sanitize-html can be used in MongoDB to validate data before storing to a database.
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With