Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

my problem is, i have photos with comments, and i want to sort them out. for example, i want to show first the photo with the most number of comments, least number of comments, newly submitted photo and old photos.

here are my schemas:

var testSchema = new mongoose.Schema({
    name: String,
    image: String,
    likes: Number,
    description: String,
    date: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Loginuser"
        },
            username: String,
            image: String,
    },
    comments: [
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
        }
    ]
});

var commentSchema = new mongoose.Schema ({
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Loginuser"
        },
        username: String,
        image: String
    },
    text: String,
    date: String
});

here is my aggregate query

db.users.aggregate([
  {$unwind: "$comments"}, 
  {$group: {_id:"$_id", comments: {$push:"$comments"}, size: {$sum:1}}}, 
  {$sort:{size:1}}]);

this is the output

{ "_id" : ObjectId("57e8570b7347ac11ec2a8a65"), "comments" : [ ObjectId("57e8852
edd0dfe08d490fa75") ], "size" : 1 }
{ "_id" : ObjectId("57e853977db98b1240d223d8"), "comments" : [ ObjectId("57e884e
ddd0dfe08d490fa73") ], "size" : 1 }
{ "_id" : ObjectId("57e88456dd0dfe08d490fa72"), "comments" : [ ObjectId("57e99ea
2e56d4913248918d4") ], "size" : 1 }
{ "_id" : ObjectId("57f2f2bd793bbe06ac565cfa"), "comments" : [ ObjectId("57f2f36
551594d10f471c86f") ], "size" : 1 }
{ "_id" : ObjectId("57e8540f7db98b1240d223da"), "comments" : [ ObjectId("57e8902
ddd0dfe08d490fa77"), ObjectId("57f2f34d51594d10f471c86e") ], "size" : 2 }
{ "_id" : ObjectId("57ead7170885a102ec31c025"), "comments" : [ ObjectId("57ead72
50885a102ec31c026"), ObjectId("57ead7350885a102ec31c027") ], "size" : 2 }

i have 2 problems here. 1st is, it doesn't show the data that has empty comment, i also want to show it. 2nd is, its only returning "_id" and "comments" data. i want to return all of the values needed like name, image, likes, description, date, author and comments

Thank you!

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.