Reputation: 9
Below is the mongoose code in 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. How to get only latest entries of both using mongoose. What should be modified in the above find condition in schema. Please help
Upvotes: 0
Views: 126
Reputation: 1126
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
Upvotes: 1
Reputation: 13662
Simplest way : find by Host_Name (one query for each name), order desc by the timestamp and limit to 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.
Upvotes: 1