Creating api using node js and mongodb | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Creating api using node js and mongodb

I am creating api of user , i have created different collection city- attribute is name of city, state - attribute is name of state. Now in third collection Address - i want to store name of city and name of state and some address attribute like pincode ,house-number,etc. My question is how to i done mapping of city ,state and Address collection. I want to add these in User Collection by mapping all these collection. please suggest me.

3rd Aug 2019, 4:23 PM
shila chavan
1 Answer
0
I'm not sure what exactly each of your collections has. You mention that you have a city collection, and that (as far as I can tell!) it only has one item in it. Essentially, your mongoose schema for this collection would be: const citySchema = new Schema({ city:String }); However, I'd generally say that's a bad idea. Yes, separation of concerns is good, but this is taking it too far. You're separating stuff enough so that, as you mention in your question, combining them becomes difficult. Why not have an "address" collection that looks something like this: const addressSchema = new Schema({ houseNum:Number, street:String, city:String, state:String, zip:String, }); If you then want to then combine multiple collections (which can be a good idea!) you can use the mongodb/mongoose "aggregate" procedure: https://masteringjs.io/tutorials/mongoose/aggregate . Keep in mind, however, that MongoDB is by design a NoSQL database, so any joining procedure (including aggregates) are, as this article (https://www.enterprisedb.com/blog/comparison-joins-mongodb-vs-postgresql) describes, rather "brittle". That is, they're easy to break and not terribly easy to use.
3rd Apr 2021, 4:47 PM
HealyUnit
HealyUnit - avatar