NodeJS Mongoose 分选

vfhzx4xs  于 2023-03-01  发布在  Node.js
关注(0)|答案(2)|浏览(143)

好吧,这是非常wierd,但排序不起作用。它没有抛出任何错误,但排序不起作用。

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

iqxoj9l91#

有关排序的一些不错的答案,请参见here,这里有一些关于mongoose async/await的很好的官方文档
您应该使用.exec()和await以获得更好的堆栈跟踪,排序可以采用以下值:一米一纳米一x、一米二纳米一x、一米三纳米一x、一米四纳米一x、一米五纳米一x和一米六纳米一x。

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

你可以看到返回的属性是经过排序的,这让我假设,你已经把minimumPrice作为字符串插入了某个地方。

pkwftd7m

pkwftd7m2#

.sort()链接适用于await

const getAllProducts = async (req, res) => {

    const { featured, company, name, sortWith } = req.query;

    const queryObject = {}

    if (featured) {
        queryObject.featured = featured === 'true' ? true : false;
    }
    if (company) {
        queryObject.company = company;
    }
    if (name) {
        queryObject.name = { $regex: name, $options: 'i' };
    }

    // here I'm sorting with provided query in sotWith or by default sorting latest products using 'createdAt' from mongoDB

    const products = await Product.find(queryObject).sort(sortWith ? sortWith.split(',').join(' ') : 'createdAt');

    res.status(200).json({ products, nbHits: products.length });
}

相关问题