简体   繁体   中英

How to sort documents depending on the sort of populated reference in MongoDB Mongoose?

I'm new in MongoDB Mongoose and I don't know if it is possible to get shops sorted on their location. I tried this query

    shop.find({},{'shopName':1,'shopLocationId':1})
    .populate({path:'shopLocationId',match:{loc:{$nearSphere:{$geometry:{type:'Point',coordinates:[50,55]}}}},select:'loc -_id'})
.exec(function (err,shops) {
        if (err)
            throw err
        console.log(shops.toString())

        })
    }) 

but I get the wrong result only shops without sort.

var ShopSchema = new Schema({
    shopName: {type: String},
    shopLocationId: {type: Schema.Types.ObjectId, ref: 'location'}
})
var LocationSchema = new Schema({
    loc:{type: Schema.Types,`enter code here`
        coordinates :[ Number]},
    locationName:{ type: String
    }
})

您可以添加排序作为选项: .populate(..., options: { sort: { 'fieldToSort': 'descending' } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM