Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 803
ZeMoon Avatar asked Feb 20 '15 14:02

ZeMoon


People also ask

Does Mongoose need schema?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

What does $Set do in Mongoose?

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.

Can I use Mongoose without MongoDB?

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.

What is _v in MongoDB?

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 ).


1 Answers

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
like image 51
JohnnyHK Avatar answered Sep 23 '22 01:09

JohnnyHK