I have two models, Job model and Tag model. The Job model has a list of tags associated with it.
I want to find all tags, and for each tag annotate a "job count" which contains the number of jobs that have that tag associated with it.
/**
* Job Schema
*/
var JobSchema = new Schema({
title: {type: String, required: true},
url: String,
skillTags: [{type: Schema.ObjectId, ref: 'Tag', index: true, required: true}],
roleTags: [{type: Schema.ObjectId, ref: 'Tag', index: true, required: true}]
}, {
toObject: {virtuals: true},
toJSON: {virtuals: true}
});
/**
* Tag Schema
*/
var TagSchema = new Schema({
name: { type: String, required: true, unique: true },
type: { type: String, values: types, required: true, index: true },
active: { type: Boolean, default: true },
slug: { type: String, unique: true },
created_at: Date,
updated_at: Date
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
/**
* Get tags
*/
exports.list = function (req, res) {
Tag.find(whereData)
.sort(sortData)
.limit(filter.limit)
.skip(filter.skip)
.execQ()
.then(function (tags) {
//not sure the most efficient way to do this
utils.tag.getJobCountByTags(tags, user)
.then(function(tagsWithCount){
res.json(tagsWithCount);
});
})
.fail(function(err){
res.send(err);
});
};