MongoDB is experiencing an issue where the latest document is not being stored at the

Storing comments for my webpage in MongoDB has been flawless so far. Whenever a new comment is saved, it gets added to the bottom of the collection. This results in the newest comment appearing at the top when loading comments, which is ideal. However, I encountered an issue when adding a 124-character comment - all subsequent comments are now being positioned second to last. It seems like the 124-character comment is stuck at the top. Comments with less than 124 characters do not cause any problems. The only workaround currently is to delete the problematic comment. The timestamps for each comment are correct.

Although I don't think it's the root cause of the problem, below is the schema utilized:

    var commentSchema = new Schema({
        username: { type: String },
        comment: { type: String },
        timePosted: { type: Date, dafault: new Date() },
        upVotes: { type: Number, default: 0 },
        downVotes: { type: Number, default: 0 }
    });

Outlined here is a simplified version of how the comment information is posted to the database:

router.post('/addComment', function(req, res, next) {
    comment = new Comment(req.body);
    comment.comment = comment.comment.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    comment.save(function(err, savedComment) {
        if (err) { throw err; }
        res.json(savedComment);
    });
});

The three latest entries in the collection are as follows:

/* 48 */
{
    "_id" : ObjectId("5dc33349673dc30ed49d53dc"),
    "upVotes" : 0,
    "downVotes" : 0,
    "comment" : "unce unce unce",
    "username" : "mcChicken",
    "timePosted" : ISODate("2019-11-06T20:55:37.955Z"),
    "__v" : 0
}

/* 49 */
{
    "_id" : ObjectId("5dc3334d673dc30ed49d53dd"),
    "upVotes" : 0,
    "downVotes" : 0,
    "comment" : "yes",
    "username" : "mcChicken",
    "timePosted" : ISODate("2019-11-06T20:55:41.927Z"),
    "__v" : 0
}

/* 50 */
{
    "_id" : ObjectId("5dc2e1dd7d13ba16effdeaa7"),
    "upVotes" : 0,
    "downVotes" : 0,
    "comment" : "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
    "username" : "mcChicken",
    "timePosted" : ISODate("2019-11-06T15:08:13.237Z"),
    "__v" : 0
}

I have attempted researching the order in which MongoDB saves documents but haven't found a solution yet. Any insight would be greatly appreciated as I am perplexed by this issue.

Answer №1

When executing a find() query in MongoDB without specifying a sort order, the resulting documents are returned in an arbitrary sequence, with no inherent ordering present.

It may appear that the documents are ordered during testing, but this is merely coincidental and can change when new documents are added to the collection.

To ensure that your output is properly sorted, you should include a sort() parameter in your query. Failure to do so means the documents will not be guaranteed to be returned in a specific order.

For efficient sorting, it is recommended to create an index that supports the desired sort criteria, as outlined in the tutorial on sorting results using indexes provided in Use Indexes to Sort Query Results. Without proper indexing, MongoDB's in-memory sorting capabilities are limited to 32 MB of memory usage. Queries exceeding this limit will result in an error.

Answer №2

After investigating why the documents were stored in the wrong order, I managed to resolve the issue by implementing a query sorting method. Below is the code snippet I utilized for this purpose:

    Comment.find({}).sort({timePosted:1}).exec( (err, comments) => {
        if (err) { throw err; }
        res.json(comments);
    });

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

Is it necessary for the schema to be an exact match in order to retrieve any data? (using mongoose

I have a simple backend setup with a client to display data from a mongo db. The data is stored in a collection called cards within a database named test. When I execute the regex from this file, I get one document in return. However, when I try to search ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

What is the best way to incorporate template literals (` `) into existing template literals?

I am facing a unique challenge where I need to utilize a template literal within another template literal, but I am struggling to make it work. The code snippet in question looks like this: <p>Something something <a href={`${SOMELINK}/blah`}> ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

What is the best way to transfer an array from an Express Server to an AJAX response?

My AJAX request successfully communicates with the server and receives a response that looks like this: [{name: 'example1'}, {name: 'example2'}] The issue arises when the response is passed to the client-side JavaScript code - it is t ...

Is there an npm module available that can automate a daily task at a specified time in a Node.js environment?

Searching for an NPM Module to integrate into a Node.js application that can send notifications via email and SMS daily at 9am local time. Any suggestions or solutions would be greatly appreciated! ...

Is there a more efficient approach to configuring properties in AngularJS while maintaining a binding?

When trying to set a property in a service equal to data returned from a network call, the conventional method goes like this: //SERVICE// thisService.property = data; //SERVICE// The corresponding controller code usually looks something like this: //CO ...

Hide the popup by clicking anywhere outside of it

I need help with a code that involves a button triggering a popup, and I want the user to be able to close the popup by clicking outside of it when it's open. My goal is to assign the method "Close()" to the event listener that detects clicks outside ...

struggling to navigate the request to a different HTML page from the controller using AngularJS

Having a situation where I need Page A to render Page B with the values entered on Page A upon submission. Page A is connected to controller A, and when the click event triggers, the Spring controller renders Page B. The problem I'm encountering is t ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

How can I decrease the size of a picker in React Native?

My example shows that the picker displays numbers, but the size of it is too long and covers the entire screen. I want to reduce its size. How do I do it? In this code, I have built a dropdown list picker that contains numbers 1-31. I tried to reduce the ...

Place a <div></div> element within a collapsible accordion container that conceals the content inside the <div>

My accordion is expanding, but the div inside it appears blank instead of displaying its content. Any suggestions on how to fix this? Thank you. How can I ensure that the div inside the accordion shows its content? Here is the code: http://jsfiddle.net/6 ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

Accessing Public Photos from Facebook Users

Is it possible to create a web app that can retrieve all public photos from any user's Facebook account using their profile URL? For instance, some Facebook profiles allow non-logged in users to view profile pictures and cover photos. I am developing ...

Utilizing Node.js to retrieve streams in conjunction with OpenAI

I am currently working on setting up a node/react setup to stream results from openai. I came across an example project that accomplishes this using next.js. While I have successfully made the API call and received the results as expected, the challenge li ...

Is there a way to anticipate and address issues that are not directly related to the code, such as internet connectivity problems, in order to minimize disruptions?

Currently, I am in the process of developing code that can automatically download and unzip a file from a website. The code is set up to check for the latest version of the file every 4 hours, ensuring it doesn't redownload if already up to date. Howe ...

A ServerSessionPool is needed in MongoDB replication for ClientSession - NODEJS

I encountered the following error related to a mongo replica set, but could not find any documentation about it ClientSession requires a ServerSessionPool I am running multiple Node.js services that utilize the MongoDB node driver. Does anyone have any ...

Incorporating user preferences and approval functionality within Mongoose schemas

I am working on creating a database that stores information about users and their preferences in a "Library" database. The concept is outlined below: User Model const userSchema = Schema({ username: {type: String, minlength: 4, maxlength: 10, require ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...