I have an article outline that has a subdocument commentsthat contains all the comments I received for this particular article.
What I want to do is select the article by id, fill in its authorβs field, as well as the authorβs field in the comments. Then sort the comment tag by date.
outline of the article:
var articleSchema = new Schema({
title: { type: String, default: '', trim: true },
body: { type: String, default: '', trim: true },
author: { type: Schema.ObjectId, ref: 'User' },
comments: [{
body: { type: String, default: '' },
author: { type: Schema.ObjectId, ref: 'User' },
created_at: { type : Date, default : Date.now, get: getCreatedAtDate }
}],
tags: { type: [], get: getTags, set: setTags },
image: {
cdnUri: String,
files: []
},
created_at: { type : Date, default : Date.now, get: getCreatedAtDate }
});
static method in the article outline: (I would like to sort the comments here, can I do this?)
load: function (id, cb) {
this.findOne({ _id: id })
.populate('author', 'email profile')
.populate('comments.author')
.exec(cb);
},
I need to sort it elsewhere:
exports.load = function (req, res, next, id) {
var User = require('../models/User');
Article.load(id, function (err, article) {
var sorted = article.toObject({ getters: true });
sorted.comments = _.sortBy(sorted.comments, 'created_at').reverse();
req.article = sorted;
next();
});
};
I call toObjectto convert a document to a javascript object, I can save my getters / virtual machines, but what about the methods?
In any case, I do the sorting logic on a regular object and I do.
I am sure there is a much better way to do this, please let me know.