node.js - How to sort, select and query subdocument in mongoose -
so i'm trying sort subdocument, select , everything. seems can't regular query tried w/ aggregate
mongoose = require("mongoose"); mongoose.connect("localhost:27017", function(err) { mongoose.connection.db.dropdatabase(); story = mongoose.model("story", { title: string, comments: [{ author: string, content: string }] }); sample = new story({ title: "foobar", comments: [ { author: "a author", content: "1 content" }, { author: "b author", content: "2 content" } ] }); sample.save(function(err, doc) { story.aggregate([ { $match: { _id: doc._id }}, { $unwind: "$comments" }, { $project: {"comments": 1}}, { $sort: {"comments.author": -1}} ], function (err, result) { if (err) { console.log(err); return; } console.log(result); }); }) });
this work:
[ { _id: 541c0f8098f85ac41c240de4, comments: { author: 'b author', content: '2 content', _id: 541c0f8098f85ac41c240de5 } }, { _id: 541c0f8098f85ac41c240de4, comments: { author: 'a author', content: '1 content', _id: 541c0f8098f85ac41c240de6 } } ]
but i'd like:
[ { author: 'b author', content: '2 content', _id: 541c0f8098f85ac41c240de5 }, { author: 'a author', content: '1 content', _id: 541c0f8098f85ac41c240de6 } ]
i use lodash's pluck there way mongodb?
you can change $project
reshape output provide structure you're looking for:
story.aggregate([ { $unwind: "$comments" }, { $project: { author: '$comments.author', content: '$comments.content', _id: '$comments._id' }}, { $sort: {author: -1}} ], function (err, result) { ...
output:
[ { _id: 541c2776149002af52ed3c4a, author: 'b author', content: '2 content' }, { _id: 541c2776149002af52ed3c4b, author: 'a author', content: '1 content' } ]
Comments
Post a Comment