简体   繁体   English

如何寻找文件

[英]How to find documents

Below is the mongoose code in app.js 以下是app.js中的猫鼬代码

app.get('/view', function (req, res) {


if (err) return handleError(err);

    {

); ); }); });

I have two different host entries that is Host_name:Redhat1,Host_name:Redhat2. 我有两个不同的主机条目,分别是Host_name:Redhat1,Host_name:Redhat2。 How to get only latest entries of both using mongoose. 如何使用猫鼬仅获取两者的最新条目。 What should be modified in the above find condition in schema. 以上在架构中的查找条件中应修改的内容。 Please help 请帮忙

Simplest way : find by Host_Name (one query for each name), order desc by the timestamp and limit to 1. 最简单的方法:按Host_Name查找(每个名称一个查询),按时间戳排序desc并将其限制为1。

// needed to tell mongoose to use ES6 Promises
require('mongoose').Promise = global.Promise;

app.get('/view', function (req, res) {
    var query1 = User.find({ "Host.Host_name": "RedHat1" })
        .sort({ Date.Time_stamp: -1 })
        .limit(1)
        .exec(); // exec() without argument returns a promise

    var query2 = User.find({ "Host.Host_name": "RedHat2" })
        .sort({ Date.Time_stamp: -1 })
        .limit(1)
        .exec();

    Promise.all([query1, query2])
        .then(function (docs) {
            var Users = docs.map(function (User){
                return {
                    time: User.Date.Time_stamp,
                    host: User.Host.Host_name
                }
            });
            res.render('index',{Users: Users});
        }).catch(function (err) {
            console.log(err);
        });
});

Edit: doing two queries leads to an another issue, you have to wait for both to be complete before sendind a response so I updated my example. 编辑:执行两个查询会导致另一个问题,在sendind响应之前,您必须等待两个查询都完成,所以我更新了示例。

try this one 试试这个

User.aggregate(
        { $match: { "Host.Host_name": { $in: ["RedHat1", "RedHat2"] }}}
        { $group: { _id: "$Host.Host_name", Time_stamp:{$last:'$Date.Time_stamp'}}}
       ,function (err,docs) {
        if (err) return handleError(err);
                var Users = docs.map(function (User){
                    return {
                        time: User.Time_stamp,
                        host: User._id
                    }
                });
            res.render('index',{Users: Users});
        });

Hope this will resolve your problem 希望这能解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM