【问题标题】:mongodb sorted order insertion using Mongoose in nodejsmongodb在nodejs中使用Mongoose进行排序插入
【发布时间】:2017-01-24 19:42:08
【问题描述】:

我有一个如下所示的猫鼬模式

var testdata = new Test({
        Product_Type: 10, 
        Product_ID: 'GPR',
        attrib: [   
                    {
                        Year:2017,
                        Month: 3
                    },
                    {
                       Year:2011,
                       Month: 3
                    },
                    {
                        Year:2012,
                        Month: 3
                    },
                    {
                        Year:2015,
                        Month: 3
                    }
                ],
    });

testdata.save(function(err, testdata) {
  if(err){
      console.log('saving data error',err);
  }else{
       res.status(200).json({'msg':'Data inserted'});
  }

});

当我从 mongodb 中检查时,属性信息按照架构中给出的方式存储,但我希望属性存储在 mongodb 中,如下所示

   {
        Year:2017,
        Month: 3
    },
    {
        Year:2015,
        Month: 3
    },
    {
        Year:2012,
        Month: 3
    },
    {
       Year:2011,
       Month: 3
    }

我希望atrrib信息按年月降序存储

【问题讨论】:

    标签: node.js mongodb mongoose-schema


    【解决方案1】:

    MongoDB 不会自动为您排序数据。

    如果您想存储已排序的数据,则必须在将其插入 Mongo 之前手动对其进行排序。为此你可以试试这个 -

    var testdata = new Test({
        Product_Type: 10, 
        Product_ID: 'GPR',
        attrib: [   
                    {
                        Year:2017,
                        Month: 3
                    },
                    {
                       Year:2011,
                       Month: 3
                    },
                    {
                        Year:2012,
                        Month: 3
                    },
                    {
                        Year:2015,
                        Month: 3
                    }
                ].sort(function(d1,d2) {if(d1.Year==d2.Year) return d2.Month - d1.Month; else return d2.Year - d1.Year;})
    });
    

    此排序方法将按降序对您的对象进行排序。这只是一个幼稚的实现。随意改进方法。

    如果您想将未排序的数据存储到 Mongo 中,并希望在查询数据时由 Mongo 对其进行排序,那么您必须在查询中使用 sort() 运算符。阅读它here。

    【讨论】:

    • @sarojmandal 可能您使用的是不支持箭头函数的 Node.js 版本。检查修改后的代码。
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2016-09-19
    • 2023-03-27
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多