Find the earliest date of an object with a different condition in mongodb using javascript / node.js

Right now, let's say I have a database defined in the model file, like:

MessageSchema = mongoose.Schema({
  message:       String, 
  sessionRef:     { type: mongoose.Schema.Types.ObjectId, ref:'Session' },
  dateCreated:      { type: Date, default: Date.now }
});

In another file, I declare the message as:

var Message  = require("../models/message");

Now I want to create a query using mongoose that finds the earliest message with a specific sessionRef. For example:

Message.find({sessionRef : 123456})

This can be used to search for messages with a specific sessionRef, but how do I actually find the earliest message (sorted by date)?

+4
source share
1 answer

Sort by earliest date:

Message.find({sessionRef : 123456})
 .sort({'dateCreated': 'desc'})
 .exec(function(err, messages) {
     //first item is a earliest message
 });

or if you want to return only one element, you can use findOne:

Message.findOne({sessionRef : 123456})
 .sort({'dateCreated': 'desc'})
 .exec(function(err, message) {
     //the message is the earliest
 });
+5
source

All Articles