【问题标题】:how to sort elements on the basis of populated object in mongodb (mongoose)如何根据 mongodb (mongoose) 中的填充对象对元素进行排序
【发布时间】:2019-06-17 20:11:24
【问题描述】:

我有两个架构钱包和用户

用户架构:-

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)
 })

但是他们两个都没有工作,我搜索了很多,但我没有得到任何适当的解决方案,有没有其他方法可以做到这一点,因为我知道我对此感到沮丧。

提前致谢

【问题讨论】:

    标签: node.js mongoose


    【解决方案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}}
    ]);
    

    【讨论】:

    • 谢谢兄弟,但我可以在不使用聚合查询的情况下做同样的想法
    • 是的,尝试上述解决方案,无需聚合
    • 我将尝试使用find() 复制您的问题,如果我有解决方案则发布
    • 您无法对填充的字段进行排序。因此,在 mongodb 中排序的唯一方法是使用aggregate。答案已修改!
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多