Mongoose subdocument sort

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.

+4
2

, , -, " ".

, , "" . " " Object , .


, "" "created_at", :

  • "" " ", "" , , "" ( ) MongoDB $position $push:

    Article.update(
        { "_id": articleId },
        { 
            "$push": { "comments": { "$each": [newComment], "$position": 0 } }
        },
        function(err,result) {
            // other work in here
        }
    );
    

    "" "first" (0), .

  • "" , " ", " " $sort $push:

    Article.update(
        { "_id": articleId },
        { 
            "$push": { 
                "comments": { 
                    "$each": [newComment], 
                    "$sort": { "$created_at": -1 } 
                }
            }
        },
        function(err,result) {
            // other work in here
        }
    );
    

    "" , . :

    Article.update(
        {  },
        { 
            "$push": { 
                "comments": { 
                    "$each": [], 
                    "$sort": { "$created_at": -1 } 
                }
            }
        },
        { "multi": true },
        function(err,result) {
            // other work in here
        }
    );
    

    "" .

.aggregate() / " " mongoose .sort() .

"" , "" . , , , -, , , " ", .

, , "", "" .toObject() , , .

- "" , "created_at" , "" , , "" , , .

+5

Array sort JavaScript , :

// Convert the mongoose doc into a 'vanilla' Array:
const articles = yourArticleDocs.toObject();

articles.comments.sort((a, b) => {
  const aDate = new Date(a.updated_at);
  const bDate = new Date(b.updated_at);

  if (aDate < bDate) return -1;
  if (aDate > bDate) return 1;

  return 0;
});
0

All Articles