Le Qs Le Qs - 1 year ago 64
Javascript Question

Error getting a single value from a collection

I have a collection called notification and i am trying to get a single value with findOne()

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

I want to get the value where the
and i want to get the latest record and i only want one record.

Even though
is part of the row fields,i get the error that
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"

Why is

Answer Source

There are four basic possibilities why Collection.findOne(query).key could yield an error:

  1. There is no document matching the query therefore you're trying to reference undefined.key
  2. The key in question doesn't exist in the returned document
  3. The document exists in the database but isn't being published by the server and being subscribed to by the client
  4. The document exists and is published and subscribed to but the subscription is not yet .ready(), i.e. you need to wait before you can access it.

A common defensive pattern is:

const oneDoc = myCollection.findOne(query);
let myVar = oneDoc && oneDoc.key;
if ( myVar ) {
  // do the thing
} else {
  // handle the error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download