Home > Software design >  How to model a collection in nodejs mongodb
How to model a collection in nodejs mongodb

Time:01-03

Hello I am new to nodejs and mongodb.

I have 3 models:

  1. "user" with fields "name phone"
  2. "Shop" with fields "name, address"
  3. "Member" with fields "shop user status". (shop and user hold the "id" of respective collections).

Now when I create "shops" api to fetch all shop, then I need to add extra field "isShopJoined" which is not part of the model. This extra field will true if user who see that shop is joined it otherwise it will be false.

The problem happens when I share my model with frontend developers like Android/iOS and others, They will not aware of that extra field until they see the API response.

So is it ok if I add extra field in shops listing which is not part of the model? Or do I need to add that extra field in model?

CodePudding user response:

Yes you have to add the field to the model because adding it to the response will be only be a temporary display of the key but what if you need that in the future or in some list filters, so its good to add it to the model.

If you are thinking that front-end will have to be informed so just go it, and also you can set some default values to the "isShopJoined" key let it be flase for the time.

CodePudding user response:

If I understood correctly, you don't have to do anything since the info is stored in the Member collection. But it forces the front-end to do an extra-request (or many extra-requests) to have both the list of Shops and to check (one by one) if the current logged user is a Member of the shop.

Keep in mind that the front-end in general is driven by the data (and so, the API/back-end), not the contrary. The front-end will have to adapt to what you give it.

If you're happy with what you have, you can just keep it that way and it will work, but that might not be very effective.

You could tackle this problem via 2 ways:

MongoDB Aggregates

When retrieving (back-end side) the list of shops, if you know the user that made the request, instead of simply returning the list of Shops, you could return an aggregate of Shops and Members resulting in an hybrid document containing both the info of Shops and Models. That way, the front-end have all the info it needs with one back-end request.

Drop the Members collection and store the info elsewhere

Instinctively, I would've gone this way. The idea is to either store an array field shopsJoined in the User model, or a membersJoined array field in the Shops model. That way, the info is retrieved no matter what, since you still have to retrieve the Shops and you already have your User.

  • Related