I have user document collection like this:
User {
id:\"001\"
name:\"John\",
age:30,
friends:[\"userId1\",\"userId2\",\"userId3\"....]
}
>
You can do it in one go using mongo-join-query. Here is how it would look like:
const joinQuery = require("mongo-join-query");
joinQuery(
mongoose.models.User,
{
find: {},
populate: ["friends"],
sort: { age: 1 },
},
(err, res) => (err ? console.log("Error:", err) : console.log("Success:", res.results))
);
The result will have your users ordered by age and all of the friends objects embedded.
Behind the scenes mongo-join-query
will use your Mongoose schema to determine which models to join and will create an aggregation pipeline that will perform the join and the query.