Jean Dupont Jean Dupont - 3 months ago 22
Javascript Question

Dynamic field names in MongoDB using Mongoose

. Sample of collection Flights :

{
"Orig" : "AGP",
"Dest" : "CMN",
"Description_Flight" : "One-Stop-Narrow Type",
"Description_Flight_2" : "WESTERN EUROPE/WESTERN EUROPE",
"Mkt_Al" : "0B"

}


. Sample of collection Coeff :

{
"Regions" : "WESTERN EUROPE/WESTERN EUROPE",
"Non-Stop-Narrow Type" : 2.4109,
"Non-Stop-Supersonic" : 2.71828,
"One-Stop-Narrow Type" : 2.22554,
"One-Stop-Turbo" : 0.92312,
"One-Stop-Wide Type" : 11.24586,
"One-Stop Online-Turbo" : 0.07577

}


What I want ?

I Have my starting collection,
Flights
and for each document I want to put a score, a score which based on the
Description_Flight_2
and
Description_Flight
.

Example :

For example, in my sample I have :

"Description_Flight" : "One-Stop-Narrow Type",
"Description_Flight_2" : "WESTERN EUROPE/WESTERN EUROPE",


So, I should go to the
Coeff
collection, and find the region :

"WESTERN EUROPE/WESTERN EUROPE"


and then take the appropriate value, here I should take this value in this line :

"One-Stop-Narrow Type" : 2.22554,


I have tried this :

mongoose.connect('mongodb://localhost/mydb');

var cSchema = new Schema({},{ strict: false, collection: 'flights' }),
dflights = mongoose.model("flights", cSchema);
var rSchema = new Schema({},{ strict: false, collection: 'coeff' }),
coeff = mongoose.model("coeff", rSchema);
mongoose.set('debug', false);

mongoose.connection.on("open", function (err) {
if (err) throw err;


dflights.find({}).lean().exec(function (err, flights) {
if (err) throw err;

flights.forEach(function(flight) {

var Flight_Description = "", score =0 ;

coeff.findOne({Regions : flight.Description_Flight_2}).lean().exec(function (err, coef) {


And here the important lines :

Flight_Description = flight.Description_Flight;
score = (coef != null ) ? coef.Flight_Description : "Missed data";


Here the last lines

if ( score != 0)
dflights.collection.update({_id:flight._id}, { $set : { score :score } } );
});
});
});
});


Please how can I achieve the above ?

Answer

The correct code should be:

score = (coef != null ) ?  coef[Flight_Description] : "Missed data";