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

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

Express get requests are failing to handle query strings

Whenever I try to extract the year and month from the URL like this: http://localhost:3000/api/posts/2018/4, the code doesn't seem to work properly. Instead, it returns an error saying: Cannot GET /api/posts/2018/4 Here's the JavaScript code I&a ...

Controlling dynamic fields within a web page - Utilizing Postgres and MongoDB databases

My application utilizes MongoDB and PostgreSQL as databases, with AngularJS for the UI. A key requirement is the ability to dynamically add fields (columns) on pages, allowing users to define their attributes when adding these fields to the system. In add ...

Tips for deactivating the highlight on a previously selected menu item when clicking on the next menu option in Angular.js

In my pages, I have a menu where the landing page menu is initially highlighted. However, when I move to the next menu, the previous landing page highlight remains instead of being removed while swapping the menu. I am using Angular.js and angular ui-route ...

Tips for displaying javascript code containing variables in the executeScript method

I'm currently working on a selenium script that involves executing JavaScript code using the executeScript method. I've run into an issue when it comes to handling single (') and double quotes (") while passing variables. Not Working: js.e ...

Discovering the data from a JSON serialization in JavaScript

Within my PrintViewModel list, there is a sublist called Summary. I am working with ASP.NET MVC. @model CRC.Models.PrintViewModel; <label id="lblTotalMonthlyLoanDeduction"></label> I am serializing it using JSON. var obj = @Json.Se ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

Select Items Based on Filtering Arrays

Within the JSON format below, there exists a state in addition to a checkbox state that signifies the selection of categories. initialData = [ { store_name: 'Shop 1', women: false, men: false, kids: true}, { store_name: 'Shop ...

Remove data from MySQL using a JavaScript function

I have a database with a list of items that I want users to be able to delete by clicking on a link. I need this to happen without refreshing the page. Although I am not very experienced with JavaScript, I am trying my best. This is how I currently have i ...

Totally at a standstill. (Problem with MongoDB in my MERN stack)

Currently developing an app, focusing on a feature that takes user input and stores it in the database. Although I've implemented this in past projects, I'm facing a persistent issue. Upon user input submission, the data is sent to the backend w ...

The error message "Cannot read property 'find' of undefined in mongodb" indicates that there is an issue with

Currently in the process of integrating mongoose into a nodejs project. Took the step to create a test record within a collection for the purpose of testing out CRUD operations from the backend, specifically interested in trying out the find() property of ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

What is the best way to create a test for my Vue component using Jest?

Below is the login form component that needs to be tested for various scenarios: Verify successful login with both username and password filled Check for input error when either username or password is left blank Ensure input error is thrown when only us ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...