I am trying to add a new static method to my Mongoose Model. The method should accept the names of several fields and return an object with the distinct values of each of those fields.
var mongoose = require('Mongoose');
var Schema = mongoose.Schema;
var mySchema = new Schema({Year: Number, Segment: String,
Sector: String, Name: String, Group: String, Value: Number});
mySchema.statics.manyDistinct = function(err, fields, callback) {
var out = {};
for (var i = 0; i < fields.length; i++) {
this.distinct(fields[i], function(err, dat) {
if (err) {
return err;
} else {
out[fields[i]] = toJSON.stringify(dat);
}
});
}
callback(err, out);
};
mongoose.model('myThing', mySchema);
Data example:
{Year: 2015, Segment: 'North', Sector: 'Alpha', Name: 'Bob', Group: 'Engineering', Value: 12}
{Year: 2012, Segment: 'North', Sector: 'Beta', Name: 'Joe', Group: 'Accounting', Value: 29}
{Year: 2013, Segment: 'South', Sector: 'Alpha', Name: 'Betty', Group: 'Accounting', Value: 6}
Calling the method and expected output:
myThing.manyDistinct(['Year', 'Segment', 'Sector'], function(err, result) {
if (err) return err;
console.log(result);
});
{Year: [2015, 2012, 2013], Segment: ['North', 'South'], Sector: ['Alpha', 'Beta']}
What I'm getting:
Error: No value for `distinct` has been declared
Please keep in mind that I'm still fairly new to JS, Node, MongoDB, and Mongoose, so I'm not 100% clear on things like the difference or situational use of lists vs arrays vs objects and some other things.
Update
Based on additional research I'm beginning to wonder if this a problem for async.map()
. I definitely could use some advice here.
Here is what I think the async.map version of manyDistinct()
should look like.
mySchema.statics.manyDistinct = function(fields, callback) {
async.map(fields, function(field, callback) {
this.distinct(field, function(err, result) {
if (err) return callback(err);
return {field: result};
})
},
function(err, results) {
if (err) {
return console.log(err);
} else {
return results;
}
})
};