Evaldas Raisutis
Evaldas Raisutis

Reputation: 1638

Mongoose - How do I query multiple models for an id?

I have models based on schemas, for ex. Users, Events, Rooms. All of these entities can have comments enabled. Comments are stored on a seperate model Comments, since I cannot control how many comments each entity might end up having. I want to be able to Find the entity by id of a comment and make the search through all the models I have. Basically something like this:

[list of models to search].Find( { comment_id: id });

Any ideas?

Upvotes: 1

Views: 1076

Answers (2)

Johnny Hall
Johnny Hall

Reputation: 545

And there's nothing to stop you from saving the data into multiple collections, so in the 'search' collection and also the separate 'users', 'events' collections.

You might even want to use a technology like solr or elastic search, to index your data.

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 146014

mongodb can search only one collection per command, so for your use case you would need a separate query for each collection.

You may consider storing all your comments in a single collection and associating them back out to their parent model by reference with modelId and modelName fields. I have used that schema successfully. It sounds like you are storing your comments as an array of comment IDs in your parent model, which seems less practical than either fully embedding the comments or fully separating them.

Upvotes: 1

Related Questions