query a job count for each tag in mongoose

36 views
Skip to first unread message

Anthony Ettinger

unread,
Jun 28, 2015, 3:23:53 PM6/28/15
to mongoo...@googlegroups.com
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.

What is the best way to do this?

Here is my model:


/**
* 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);
});
};

Reply all
Reply to author
Forward
0 new messages