如何填充数组的日期并对填充的数据进行排序

时间:2018-01-05 05:32:46

标签: node.js mongodb sorting express mongoose

我在mongoose中有这个架构:

var schema = new Schema({
name: {type: String, required: true},
description: {type: String, required: true},
subcategory: {type: Schema.Types.ObjectId, ref: 'SubCategory'},
price: [{type: Schema.Types.ObjectId, ref: 'Price'}],
provider: [{type: Schema.Types.ObjectId, ref: 'Provider'}]
});

var schema = new Schema({
monto: {type: Float, required: true},
fecha: {type: Date, required: true},
idProvider: {type: Schema.Types.ObjectId, ref: 'Provider'},
idProduct: {type: Schema.Types.ObjectId, ref: 'Product'}
});

我需要填充getall产品,我需要获取每个产品的当前价格并仅显示该产品。我尝试过这样做但不起作用:

router.get('/', (req, res, next) => {
Product.find({})
.populate({path: 'price', options: { $sort: {'fecha': -1}, limit: 1}})
.then(product => {
    if(!product) {return res.sendStatus(401);}
    return res.json(product)
})
.catch(next);
})

例如:

{
  "_id": "5a4eebdd24b0412d0cf58601",
  "name": "Heladera",
  "description": "Automatico con centrifugado",
  "__v": 1,
  "provider": [],
  "price": [
     {
       "_id": "5a4ea416e723b42c28fd624e",
       "monto": 8560.23,
       "fecha": "2000-12-12T03:00:00.000Z",
       "idProduct": "5a4ea3b3e723b42c28fd624d",
       "__v": 0
      }
      {
       "_id": "5a4f0741f722c01528582104",
       "monto": 900,
       "fecha": "2018-12-12T03:00:00.000Z",
       "idProduct": "5a4f072ff722c01528582103",
       "__v": 0
        }
    ]
}

我需要展示

{
    "_id": "5a4eebdd24b0412d0cf58601",
    "name": "Heladera",
    "description": "Automatico con centrifugado",
    "__v": 1,
    "provider": [],
    "price": [
        { monto: 900}
     ]
 }

1 个答案:

答案 0 :(得分:1)

您可以编写这样的聚合管道。

db.products.aggregate([
  { $unwind: "$price" },
  { $sort: { "_id": 1, "price.fecha": -1 } },
  { $group: { _id: "$_id", product: { $first: "$$ROOT" } } }
]);

这将为您提供以下文件。

{
    "_id" : "5a4eebdd24b0412d0cf58601",
    "product" : {
        "_id" : "5a4eebdd24b0412d0cf58601",
        "name" : "Heladera",
        "description" : "Automatico con centrifugado",
        "__v" : 1.0,
        "provider" : [],
        "price" : {
            "_id" : "5a4f0741f722c01528582104",
            "monto" : 900.0,
            "fecha" : "2018-12-12T03:00:00.000Z",
            "idProduct" : "5a4f072ff722c01528582103",
            "__v" : 0.0
        }
    }
}

如果您只需要价格信息,可以添加项目阶段以重新整形返回的文档。

例如,将此最后阶段添加到上述管道

{ $project: { 
    _id: 1, 
    name: "$product.name", 
    description: "$product.description", 
    __v: "$product.__v", 
    "monto": "$product.price.monto" 
}}

文件重新整形如下。

{
    "_id" : "5a4eebdd24b0412d0cf58601",
    "name" : "Heladera",
    "description" : "Automatico con centrifugado",
    "__v" : 1.0,
    "monto" : 900.0
}