2

i have a two schema wallet and user

user schema :-

var schema = new mongoose.Schema({
 first_name: {
     type: String,
 },
 wallet_id:{
     type: mongoose.Schema.Types.ObjectId,
     ref: 'wallet'
 },
}
module.exports = mongoose.model('user', schema);

wallet schema :-

var schema = new mongoose.Schema({
   amount: {
      type: String,
   },
}
module.exports = mongoose.model('wallet', schema);

i want to find all users and sort them according to their available wallet amount and i tried allot but i did not able to do so

here is me code

//------------ this is my first try ------------

db['user'].find({})
 .populate({
    path: 'wallet',
    options: { sort: {amount:1}}
 })
 .then(res=>{
    console.log(res)
 })
 .catch(err=>{
    console.log(err)
 })

//------------ this is my second try ------------

db['user'].find({})
 .populate({
    path: 'wallet',
 })
 .sort({'wallet.amount':1})
 .then(res=>{
    console.log(res)
 })
 .catch(err=>{
    console.log(err)
 })

but both of them are not working at all i search alote but i am not getting any proper solution for that is there any other way to do this because know i am getting frusted with this.

thanks in advance

Ali Asgher Badshah
  • 811
  • 1
  • 11
  • 34

1 Answers1

4

You can't sort on virtual fields or populated fields as those fields are only present in your app objects (Mongoose model instances) but the sort is executed within MongoDB.

Reference:

You can also use aggregate on MongoDB.

db.getCollection('user').aggregate([
    { $lookup: { from: "wallet", localField: "wallet_id", foreignField: "_id", as: "wallet" }},
    { $unwind: "$wallet" },
    { $sort: {'wallet.amount': 1}}
]);
Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34