Unable to retrieve a singular data point from a set

I am currently working with a collection named notification and my goal is to retrieve a single value using the findOne() method.

 var allnotices = Notifications.findOne({eventownernumber:"2"},{sort: {noticedate: -1, limit: 1}}).noticemessage;

The desired outcome is to fetch the value where the eventownernumber equals 2, obtain the latest record, and only receive one record at a time.

Despite the fact that noticemessage is among the row fields, I am encountering an error indicating that noticemessage is undefined.

This is the schema:

{
    "_id": "tmkWCydSKZtYdrKTZ",
    "eventoriginalid": "3bXvARk6K6yhee6Hi",
    "lat": "-1.851881824302658",
    "lng": "96.987469482421875",
    "eventownernumber": "1",
    "eventownernames": "Test 1",
    "eventtitle": "ci",
    "eventtime": "08:05",
    "invited": "0",
    "eventduration": "21",
    "eventtype": "notification",
    "eventcategory": "hackathon",
    "eventstatus": "11",
    "createdAt": {
        "$date": "2016-11-02T12:38:40.378Z"
    },
    "noticedate": {
        "$date": "2016-11-02T16:50:53.394Z"
    },
    "noticenumber": "2",
    "noticenames": "Test 2",
    "noticemessage": "Test 2 has joined your event ci",
    "noticestatus": "12"
}

The question remains: Why does noticemessage appear as undefined?

Answer №1

When using Collection.findOne(query).key, there are several reasons why it could result in an error:

  1. The query may not have a matching document, leading to undefined.key
  2. The specified key may not exist in the returned document
  3. The document might be in the database but not being published by the server or subscribed to by the client
  4. The document may be published and subscribed to, but the subscription is not yet ready for access with .ready()

To tackle this issue, many developers employ the following defensive pattern:

const oneDoc = myCollection.findOne(query);
let myVar = oneDoc && oneDoc.key;
if ( myVar ) {
  // perform the necessary action
} else {
  // handle the error appropriately
}

Answer №2

Make sure to save the number as an integer for eventownernnumber (and write it like eventOwnerNumber for better readability). You can either use input type="number" or convert the value to an integer like so:

Number(valueHere);

Everything else in your query seems fine, but you don't need a limit since you are using findOne() and finding the newest inserted document with noticedate: -1

Additionally, make sure to save the date like this in your insert():

noticeDate: new Date() // After making this change, your current query should retrieve the correct document

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

Grunt replace throwing an undefined destination error

I'm attempting to use grunt replace in order to modify file names and append a random number to prevent caching of images, CSS, and JS files. Here is the code I am running: module.exports = function replace(grunt) { var randomVersion = ((new Dat ...

Having issue with jQuery popup not functioning correctly on the right side with the contact form. Is there anyone who knows how

Looking for a side slide popup that only accepts paragraph content? Want to add a contact form to it? Check out this fiddle - link here For a working example, visit - $(function() { // Slide from right to left $('#test2').PopupLayer({ ...

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

What is the best way to print the contents of an HTML element to the console in JavaScript?

I need to display the phrase "Jingle All the Way [Family Fun Edition] [DVD] [1996]" on the console from this Best Buy link. I am using axios and cheerio for this task. (async () =>{ const { data } = await axios.get(productUrl); const $ = cheerio.l ...

Merge the properties of two class instances deeply

What is the best method for deep merging two instances of ES6 classes similar to lodash? The end result should be an instance of the same class with a deep merge of both instances' properties. ...

Perform a search within an iframe

Despite the fact that iframes are considered outdated, I am attempting to create a browser within an HTML browser. I have implemented a search bar that opens the typed input in a new window which searches Google. However, I would like to modify it so that ...

Is there a way to activate an event listener specifically for clicking on an image?

Presently, my code consists of a div element that holds two images. The first image has a z-index of 1 and appears behind the second image. I am looking to implement an event listener that will be triggered only when the first image is clicked. Interestin ...

The form is refusing to submit even after using the "return false

Even after adding validation to the form, it still submits when the script returns false. The Form Submission <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this); return false;"> Javascript Code function ch ...

Encountering a problem when attempting to manually create a featherlight gallery in JavaScript using a list of hrefs: "Error: Unable to call c.first as it

Trying to manually create a featherlight gallery in Javascript by providing a list of hrefs (simple path strings) using: $.featherlightGallery(images); However, I encountered an issue: 'TypeError: c.first is not a function. (In 'c.first()&ap ...

Node.js encounters a conflict between route names and directory names

Can you use the same name for both a route and a directory in a Node.js project? For example: require("./test")(router); And inside the test.js file: app.get("/test", function(req, res) {}); Also, test is a directory in the same project. When attempti ...

Is There a Workaround for XMLHttpRequest Cannot Load When Using jQuery .load() with Relative Path?

My current project is stored locally, with a specific directory structure that I've simplified for clarity. What I'm aiming to do is include an external HTML file as the contents of a <header> element in my index.html file without manually ...

Modifying data in MongoDB

In my mongodb model, I have a User collection with a mixed schema type field called "inventory" that holds all the items owned by a user. My goal is to iterate through each user and update the name of each item in their inventory. Specifically, I want to c ...

Is there a way to verify within the "if" statement without repeating the code?

Is there a way in javascript (or typescript) to prevent redundant object rewriting within an if statement condition? For example: if (A != null || A != B) { // do something here } // can it be done like this: if (A != null || != B) { // avoid repeating ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

Angular - Triggering actions with ng-hide and ng-show events

Is there a better solution for monitoring hide and show expressions across all elements in my app? I am aware that I can achieve this by wrapping the show directive with a function that simply returns the argument: <div ng-show="catchShow(myShowExpr = ...

Error encountered while trying to install the node module, code 1. Installation failed

npm ERR! code 1 npm ERR! path D:\Neneng\a) Neneng_Pribadi File\2] Raynar abiyu diera\Rays DEV\Atomic BOT\node_modules\canvas npm ERR! command failed npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c ...

The functionality for the "OnChange" event in the <html:select> field does not seem to be functioning properly

My JavaScript function isn't functioning properly. I can't see any alert messages on my webpage. Can someone please assist me? Below is my HTML code function checkProjectStatus() { alert("Helloo"); var dropdownType = document.getElementById( ...

What is the best way to attach a Label to a THREE.Mesh object?

I'm looking to show the name of a Three.js Three.Mesh as a label when hovering over the mesh. Does anyone know how to achieve this in Three.js? Could someone provide an example code snippet for this? ...

Stuck at the STARTUP stage: MongoDB 3.6 replication issue

I have set up a MongoDB configuration with two servers located in Italy and France. The server in France is running Ubuntu server as the Primary of the replica set and functions properly, accepting connections from the mongo shell locally and remotely whil ...