How to retrieve the latest document from every sender within a JavaScript array using Mongoose/MongoDB queries

I recently created a schema:

var messageSchema = mongoose.Schema({
    sender:String,
    recipient:String,
    content:String,
    messageType: Number,
    timestamp: {type: Date, default: Date.now}
});

Next, I defined a model for this schema:

var Message = mongoose.model('Message', messageSchema);

In addition to that, I have an array of IDs/names:

var idArray = [1,2,3,4,5];

My goal is to query and retrieve the latest message document from each sender in the idArray:

var query = Message.find(
        {from: { $in: friendsOnline }},
        {timestamp: { $last: "$timestamp" }}
        });

query.exec(function (err,result){
        if(err){ console.log("An error occurred while querying.");}
        else{
            if(result!=null) {console.log(JSON.stringify(result));}
            else{console.log('No results found.');}
        }
});

I attempted something similar to the above code, but it didn't produce the desired results.

Answer №1

To retrieve the latest message sent by each sender in the idArray, you can execute a query that searches for documents based on the sender ID, limits the results to one document per sender, and sorts them by their creation time:

const query = Chat.find({ 
    sender: idArray[0]
}).
limit(1).
sort( { created: -1 } ).
exec(callbackFunction)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a custom chrome browser extension designed specifically for sharing posts on

I'm working on creating a basic chrome extension that features an icon. When the icon is clicked, I want the official Twitter window to pop up (similar to what you see here). One common issue with existing extensions is that the Twitter window remains ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

The issue of Angular JQuery Datepicker failing to set the MinDate upon initialization

In my AngularJS project, I am using JQuery UI's Datepicker for the Date From and Date To fields. I have successfully bound the value to the model using a directive, and I have also implemented logic in the OnSelect function to ensure that the Date To ...

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Issue with VueJS where the datalist input does not reset the value

I am currently working on a Vue component that scans QR codes and adds information to a database upon successful scanning. The scanning process works perfectly fine. However, after successfully sending the data, I need to clear the input field in my datali ...

Parsing and Displaying JSON Data from a Python DataFrame in D3

Trying to create a stock chart, I encountered an issue with parsing the json file output by my python dataframe. The example code from http://bl.ocks.org/mbostock/3884955 does not seem to fit the format of my data: The json looks like this: var dataset = ...

Issue with VueJS rendering data within a for loop

As a newcomer to VueJS, I appreciate your patience as I navigate through this. Let me provide as much detail as possible. I am currently working on a Vue app that needs to retrieve a response from a server, iterate through the data, and set a Vue data var ...

How to effectively compare time duration with a timer in the Laravel framework

I am managing a table that stores various job entries for employees. Each job entry includes a column for duration. I would like to trigger an alert or other event when the duration of a job has ended. My project is built using Laravel and VueJS. Below i ...

Do I need to include a callback in my AWS Lambda handler function?

What is the function of the callback in the lambda handler? It appears to be utilizing the sns variable and I am looking to make some modifications to the variables. exports.handler = function(event, context, callback) { console.log("AWS lambda and ...

[next-auth][error][adapter_error_getUserByAccount]; Unable to access attributes of an unspecified item (viewing 'findUnique')

Currently, I am developing a sign up page that integrates with three popular providers (Twitter, Facebook, and Instagram) using next-auth in combination with Prisma and MongoDB. However, I have encountered an issue while attempting to sign up using any of ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

Order of Execution for Nested Promises

Curious about nested promises, I came across this coding challenge in my tutorials. Can someone shed some light on the execution order of this code? new Promise((resolve) => { new Promise((res) => { console.log("c"); resolve(3); ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

The last value label in Google Charts bar chart getting cut off

I've searched extensively for a solution to this issue regarding the haxis labels, but I have not been able to find one that addresses it... In the image provided below, you'll observe that the last percentage label on the horizontal axis is mis ...

Having trouble with a JavaScript element not responding to clicks when displayed inline?

Currently, I am utilizing the "Hotel Datepicker" script found at this website: My goal is to have the datepicker always displayed inline, rather than closing after selecting dates. I attempted to add a function that triggers whenever the datepicker close ...