node.js - what's the ideal way to deal with countries as a property on an object in mongoose (mongodb) -


i have property called country on jobschema required string.

basically gets iso-2 letter code (ie: us, nz or whatever)...and that's gets saved in database object's country property.

however have countries.json file on filesystem contains object containing full name (ie: united states) , lat/long coordinates.

{     "name": "united states",     "iso2": "us",     "lat": "37.09024",     "lng": "-95.712891" } 

i don't need crud interface this. i've built api outside of database map "us" string db file object.

however, proving bit of pita.

what way handle this?

should store full country object in db , leave @ that? seems easiest route, except of country definition changes, have stale data littered across mongo db wherever data saved.

consider mongoose population:

population process of automatically replacing specified paths in document document(s) other collection(s).

you begin modifying "iso2" property of country object _id (since iso codes unique each country) , save modified object in db. next create new mongoose schema can reference in jobschema. example:

var mongoose = require('mongoose')   , schema = mongoose.schema  // job schema var jobschema = schema({     name    : string,      country : { type: string, ref: 'country' }  // populated });  var countryschema = schema({     _id   : string,     name  : string,         lat   : number,     lng   : number });  var country  = mongoose.model('country', countryschema); var job      = mongoose.model('job', jobschema); 

the ref option tells mongoose model use during population, in case country model. country property of job model declared string, same type _id used in countryschema. important match type of _id type of ref.

to see how population works, call populate method on job model query , country field in documents populated:

job.find().populate('country').exec(function (error, jobs) {    // ... }); 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -