猫鼬排序

时间:2020-07-31 12:09:34

标签: node.js mongodb mongoose

好的,这很奇怪,但是排序不起作用。它不会引发任何错误,但是排序不起作用。

try {
    properties = await Property.find({}).sort("-minimumPrice");
 
  } catch (err) {
   console.log(err)
  }

我也尝试过,但是也没用:

try {
    properties = await Property.find({}).sort({minimumPrice: "desc"});
 
  } catch (err) {
   console.log(err)
  }

1 个答案:

答案 0 :(得分:1)

有关分类和分类的一些不错的答案,请参见here here是有关猫鼬async / await的一些很好的官方文档

您应该将.exec()与await一起使用以获得更好的堆栈跟踪,排序可以采用以下值:ascdescascendingdescending,{ {1}}和1

-1

这都是假设您的try { let properties = await Property.find(query).sort({"minimumPrice": -1}).exec() } catch (err) { console.log(err) } 是正确的,并且正在检索要排序的文档。

更新

我仔细检查了您的整个情况,并使用您提供的内容进行了测试。

query

数据库输入:

const mongoose = require("mongoose");
var Schema = mongoose.Schema;
var propertySchema = new Schema({
  name: String,
  minimumPrice: Number
});
var Property = mongoose.model('Property', propertySchema);

//Testing
(async function() {
  try {
    //connect to mongo
    await mongoose.connect('mongodb://localhost:27017/testing', { useNewUrlParser: true, useUnifiedTopology: true });

    //First, delete all properties
    await Property.deleteMany({}).exec();

    let properties = [];
    //Insert 5 properties
    for (var i = 1; i < 6; i++) {
      properties.push({ name: "property" + i, minimumPrice: Math.round(Math.random() * 10000) });
    }

    //Insert all our random properties
    await Property.create(properties);

    console.log(properties);

    //Now, retrieve all our properties
    let sortedProperties = await Property.find({}).sort({ minimumPrice: -1 }).exec();

    console.log("sorted", sortedProperties);
  } catch (err) {
    console.log(err);
  }
})();

排序输出:

[                                           
  { name: 'property1', minimumPrice: 3846 },
  { name: 'property2', minimumPrice: 7910 },
  { name: 'property3', minimumPrice: 7234 },
  { name: 'property4', minimumPrice: 4444 },
  { name: 'property5', minimumPrice: 6366 } 
]                                           

您可以看到属性重新排序。这使我想起,您已将[ { name: 'property2', minimumPrice: 7910 }, { name: 'property3', minimumPrice: 7234 }, { name: 'property5', minimumPrice: 6366 }, { name: 'property4', minimumPrice: 4444, }, { name: 'property1', minimumPrice: 3846 } ] 插入为字符串。