5

I'm currently using mongoose v. 5.25, against mongoDB v.3.6.

My application is supposed to query data from many different views, for instance, a view I currently have at my DB: db.joboffers_view.find()

will return many records that have been aggregated from different collections.

For a normal collection model, I query it like so:

 const model = db.model(attribute);
 /*where attribute, can be any registered schema */
 model.find().
       then((result) => {
           resolve(result);
       }).
       catch((err) => {
           reject(err);
       });

Then way I register my models is something like this (simplified code):

//...
//abstracting boring connection methods
const db = mongoose.connection
//...

//simple model schema
const users_schema = {
   _id: ObjectId,
   another_field: String
};

//here I'm registering a schema for a VIEW, instead of normal collection
const view_schema = {
   _id: ObjectId,
   another_field: String
};
//...
//then

db.model('users', users_schema);
db.model('view', view_schema);

When I run a query from any of my registered models, I get the results just fine. However, when I run it against a model that represents a view on my mongo database, it returns an empty array.

No errors, no nothing, just an empty array.

I have looked through mongoose documentation, and I didn't find any specific method or pattern for querying a view, instead of a collection data.

It seems to be the same way I would do for any other collection I have in my system.

Am I missing something?

3 Answers3

5

I also faced the same issue and figured out the problem is that mongoose, by default, reads collection names by pluralizing the model/view name.

So when you create any view and want to use it in mongoose, either make sure your view name is plural (add s to end of view name) or pass a collection name when initializing a schema.

Example

const users_schema = {
   _id: ObjectId,
   another_field: String
};
mongoose.model('vw_user_info', users_schema, 'vw_user_info');
Chance Snow
  • 2,440
  • 1
  • 18
  • 19
Om Prakash Sharma
  • 1,682
  • 22
  • 13
0

I have same problem, but i solved it, please check the name of the view in mongodb, it must be same with db.model('view_name', view_schema);

You can open Mongoose debug by config like this mongoose.set('debug', true);

Yanga
  • 2,885
  • 1
  • 29
  • 32
0

Add 3rd argument

db.model('view', view_schema, 'view_name_in_db')