如何在mongodb(mongoose)中的填充对象的基础上对元素进行排序

时间:2019-01-24 06:43:52

标签: node.js mongoose

我有两个模式的钱包和一个用户

用户架构:-

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

钱包架构:-

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

我想找到所有用户并根据他们的可用钱包数量对其进行排序,但我尝试分配,但我无法做到这一点

这是我的代码

// ------------这是我的第一次尝试------------

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

// ------------这是我的第二次尝试------------

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

但是我都没有搜索它们,但是我都没有找到任何合适的解决方案,因为我知道对此感到沮丧。

预先感谢

1 个答案:

答案 0 :(得分:1)

您无法对虚拟字段或填充字段进行排序,因为这些字段仅存在于您的应用程序对象(Mongoose模型实例)中,但排序是在MongoDB中执行的。

参考:

您还可以在MongoDB上使用aggregate

db.getCollection('user').aggregate([
    { $lookup: { from: "wallet", localField: "wallet_id", foreignField: "_id", as: "wallet" }},
    { $unwind: "$wallet" },
    { $sort: {'wallet.amount': 1}}
]);