Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 要对查询的结果编写查询吗_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 要对查询的结果编写查询吗

Node.js 要对查询的结果编写查询吗,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个这样的代码,它用recipt_Number的最大值从mongoose中排序文档,recipt_Number是数组allRecipt的一个字段。但所有recipt还包含许多recipt_number记录,我想获取具有最大值的记录 假设您的收藏包含以下文档: .get(function(req, res){ Recipt.find({'User':req.params.name}) .sort('-allRecipt.recipt_Number')

我有一个这样的代码,它用recipt_Number的最大值从mongoose中排序文档,recipt_Number是数组allRecipt的一个字段。但所有recipt还包含许多recipt_number记录,我想获取具有最大值的记录

假设您的收藏包含以下文档:

.get(function(req, res){
    Recipt.find({'User':req.params.name})
          .sort('-allRecipt.recipt_Number') 
          .limit(1)
          .select('allRecipt')
          .exec(function(err, doc){
              if(err) res.send(err);
              console.log(doc);
    });
});
您可以尝试以下聚合集,它将返回您需要的内容:

/* 0 */
{
    "_id" : ObjectId("550999a3c89ce9e17ea01845"),
    "user" : "Chris",
    "allRecipt" : [ 
        {
            "update_time" : NumberLong(1426690563),
            "recipt_Number" : NumberLong(4)
        }
    ]
}

/* 1 */
{
    "_id" : ObjectId("550999a3c89ce9e17ea01846"),
    "user" : "Chris",
    "allRecipt" : [ 
        {
            "update_time" : NumberLong(1426690563),
            "recipt_Number" : NumberLong(8)
        }
    ]
}
返回:

Recipt.aggregate([
    {$match: {user: req.params.name}},
    {$unwind: '$allRecipt'},
    {$project:{ "allRecipt.recipt_Number": 1 }},
    {$sort:{ "allRecipt.recipt_Number": -1 }},
    {$limit: 1}    
], function (err, result) {
    if (err) {
        console.log(err);
        return;
    }
    console.log(result);
});

你能发一个例子吗?或者它的相关部分,至少……thnx……它能满足我的需求
{
    "result" : [ 
        {
            "_id" : ObjectId("550999a3c89ce9e17ea01846"),
            "allRecipt" : {
                "recipt_Number" : NumberLong(8)
            }
        }
    ],
    "ok" : 1
}