Steps to retrieve the final value in a Mongo collection

After reading a Mongo collection, I am trying to retrieve the value of the last item. I have attempted to sort the collection from oldest to newest following this StackOverflow question, and then selecting only the first item, but I am unable to extract its value.

This snippet shows how data is inserted into the collection:

'container.start': function(id) {
    var ctn = docker.getContainer(id);
    ctn.start(Meteor.bindEnvironment(function(err, data) {
      if(err){
        ErrorsContainer.upsert({

        }, {
            error: err
        });
        console.log(err);
      }else{
        console.log(data);
      }
    }));
}

Furthermore, here is the code used to read from the collection:

  'click .start'(event) {
      const idDB = this._id
      const container = InfosContainers.findOne({_id: idDB});
      const name =  container["nameContainer"];
      const idContainer = container["idContainer"];
      console.log("the container: " + name + " is going to be started. His id is: " + idContainer);
      Meteor.call("container.start",idContainer);
      //get the last error
      var error = ErrorsContainer.find({}, {sort: {_id: 1, limit: 1}});
      if(error){
        alert(error[error]); //tried error.error too
      }
  }

Can someone guide me on how to correctly access the value of the error in the collection?

Answer №1

The issue was that the collection's error included other things, requiring me to handle it in this manner:

  var lastError = ErrorsContainer.findOne({}, {sort: {_id: 1}});
  console.log(lastError.error.message);

Answer №2

carry out

{ organize: { created : -1 } }

in which created represents the time the document was generated and -1 specifies sorting in descending order (use 1 for ascending order)

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

Utilizing AJAX for seamless page transitions

After trying to navigate between pages using a JavaScript solution, I've come to the realization that it's not sufficient for my needs. I am now looking to implement AJAX navigation between pages, and my initial idea was as follows: $(document) ...

What are the most widely used NodeJS framework and library choices currently available?

I am embarking on the exciting journey of building a robust application using NodeJS. As someone new to Node, I believe it would be beneficial to gather insights from experienced developers in the field. While researching, I have come across positive feed ...

When examining the buffer property of each uploaded file, particularly when dealing with multiple files

I'm encountering an issue while trying to upload multiple files to my server using multer. Although I can access the req.files array, I am unable to retrieve the buffer property of the files. Upon attempting to log them with console.log, all I get is ...

Preventing document.getElementById from throwing errors when the element is null

Is there a way to handle null values returned by document.getElementById in JavaScript without adding if statements or checks to the code? I'm looking for a solution that allows the execution of subsequent JavaScript calls even after encountering a nu ...

ng-repeat closing function event

Looking to create a callback method that gets called every time ng-repeat is triggered. After doing some research, I found a couple of options: 1. Using ng-init with ng-repeat This approach involves calling the method using the ng-init property: <ol ...

STLLoader not working as expected in Vue component

I've been working on incorporating the THREE STLLoader to display an object within my Vue scene. (I am utilizing the Vuetify framework, although that shouldn't impact the functionality of the THREE renderer.) Despite my efforts, I am struggling ...

What is the best way to open Chrome Developer Console using Selenium?

While conducting automated tests with C#, Webdriver, and Chrome, I was exploring the use of the performance.timing.domComplete JavaScript console function through the chrome web developer tool. Here is an example of how I attempted to incorporate it into m ...

What Happens When You Click on a Link in Google News Using the Mobile Chrome Browser

When using the Chrome Browser on mobile to open a news link from Google News, a new tab is opened. To return to Google News, users can click on the white-highlighted "left arrow" below or find a small header with a "<" symbol above to navigate back. Ho ...

How can I trigger a function after a 2-minute countdown in JavaScript?

I would like to confess right away that I am not an expert in Javascript! However, I do possess the knowledge of using ajax. Despite this, I am struggling with a particular issue and require some assistance. My challenge is to create a 5-minute countdown ...

Tips for simulating JSON import using Jest in TypeScript

When it comes to unit testing in Typescript using Jest, I am looking to mock a .json file. Currently, I have a global mock set up inside my jest.config.js file which works perfectly: 'package.json': '<rootDir>/__tests__/tasks/__mocks ...

Heroku deployment of Node.js and React: The app does not have a default language specified

My attempt to deploy my first project on Heroku, which combines Node, React, and MongoDB with Mongoose, is running into an issue. When I use the command git push heroku master, I encounter this error: remote: Building source: remote: remote: ! No def ...

Protractor tests are successful when run locally, but encounter failures when executed on Travis-CI

I recently integrated end-to-end tests using Protractor into my AngularJS application. Testing them locally showed that they all pass, but upon committing to GitHub and Travis for CI, most of the tests fail. The failing tests seem to be those requiring na ...

Is there a bug causing a refresh issue with nodejs and mongodb?

I recently started working with nodejs and managed to get something working last night using mongodb on an IIS server with iisnode. :) However, I have encountered a strange issue that appears to be a refresh bug. When I visit "http://localhost/mongo.js" i ...

Unable to deactivate button using JavaScript following an AJAX request

Within my JS file, I am attempting to disable a button after making an AJAX call: $('document').ready(function() { const runField = $('input[id=run]') const runButton = $('.btn-run') const saveButton = $('.btn-save ...

Guide for exporting MongoDB database with Docker

Currently, I am utilizing the "mongoDB" image within a docker-container. Upon executing the command to export the database to a CSV file: docker exec -i 418f46e5595d mongoexport --db saveInfo --collection infoobjects --type=csv --fields _id,postLink,pos ...

Loading input datalist in Firefox postponed

My goal is to implement an input field for a username that allows users to select from a wide range of names/usernames. I want them to be able to enter a partial string from the name or username. Instead of loading the entire list initially, I aim to load ...

click events in backbone not triggering as expected

It's puzzling to me why this is happening. The situation seems very out of the ordinary. Typically, when I want an action to be triggered on a button click, I would use the following code snippet: events:{ 'click #button_name':'somefun ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Instructions on how to use WebClient in C# to download an image and retrieve it from an ASPX page using JavaScript

I have been searching for solutions to this question everywhere, but none of them seem to work for me. The goal is to download an image from the internet using an aspx page. I want to call the aspx page from JavaScript, retrieve the data, and display it i ...

What could be causing slice to fail to slice an array?

I've been using the slice function for a while now without any issues, but I'm having trouble with .slice() not actually slicing the data. Code: (why is it not working as expected?) let data data = await Models.find().sort([['points', & ...