0

I'm using NodeJS with Mongoose. I have a collection 'user' with a schema like the following:

 id: String
 name: String
 surname: String,
 otherField1: Number,
 otherFieldN: String,
 arrayField: [String],
 messages:[
        {
            date: SchemaTypes.Long,
            id: String,
            type: String,
            content: String
        }
    ],
status:String
Supposing I have more than 10K users into my collection, what's the best way to query it if I have a function that needs in different moments some (not all) information of a single user? Is it better to query all the user data in a single query and use them locally when they are needed or is it better to query only the needed field doing more than one queries into the same function?

I precise that in the second case (more queries), depending on the result of the first queries will change the fields needed by the succeeding ones

Nicola
  • 465
  • 2
  • 7
  • 19

2 Answers2

0

I think that you should make the query upon the function needs to get the information about the user. That way you don't need to save things locally.

zb22
  • 3,126
  • 3
  • 19
  • 34
0

From MongoDB perspective there is no difference performance wise: you will hit the same number of documents with or without the chaining of .select({fields you need}) since it's the query in the find that matters (see the Explain command for more info on how to analyze query in mongodb).
To improve performance on Mongo you need to create an index in your collection on the most used field you query on or eventually shard among instances.
The big impact in your case is on the Node memory side: using select is suggested if you don't need other fields in the close future; of course if you need to re-query the DB for the other fields right after then makes sense to not use select, but keep the whole user object on the first place. Note:
from Mongoose 4.0+ you can avoid the explicit use of the select command like so.

tonnoz
  • 454
  • 4
  • 12