-1

I am trying to do a simple .find() using mongoose/nodejs with mongoDB. I have a document (with field "date": "09-20-2019") in my collection (show) but I cannot seem to find it programmatically.

I have tried using MongoDB compass (db viewer software) to perform a search for what I am looking for. I passed into the search box under my collection {date: "09-20-2019"} and I was able to find the document using their search functionality so I know it should be working. I have checked that the field "date" is coming across to back end node server as the correct format and value of "09-20-2019". I am using Node.js 10.15.1

--This is from my route.js file
router.get('/shows/:date', (req, res, next)=>{
    //res.send('Retrieving the shows list');

    console.log('back end date: ' + req.params.date);

    Show.find({date: req.params.date}, function(err, result){
        if (err)
        {
            res.json(err);
        }
        else {
            console.log(result);
            res.json(result);
        }
    })
});
--This is from my show.js (mongodb schema file)
const mongoose = require('mongoose');

const ShowSchema = mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    date:{
        type: String,
        required: true
    },
  venue:{
    type: String,
    required: true
  },
  createdDate:{
    type: String,
    required: true
  }
});

const Show = module.exports = mongoose.model('Show', ShowSchema);
--This is from my service.ts file
  getShow(date)
  {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    //date is in format MM/dd/yyyy (e.g. 09-20-2019)
    return this.http.get<Show>('http://localhost:3000/api/shows/' + date);
  }
--This is from my component
    this.commentCardService.getShow(this._date).subscribe(data => {
      console.log(data);
    });

I am expecting the .find({}) operation to return with a single document from my mongoDB of the show with the date of '09-20-2019' which is the only document that is in that collection at the moment. More than one document will exist in the collection ultimately.

amcgregor
  • 1,228
  • 12
  • 29
Retro
  • 113
  • 13
  • what is collection name? Is it different from `Shows`? – Sandeep Patel Sep 21 '19 at 07:34
  • It looks like the collection name is Shows. The first time I did this I entered in the new collection manually into mongoDB compass. It looks like maybe that was the problem? It works now that I created a POST endpoint to create a 'Show' and let it create the collection itself. But now I dont understand why the collection is called 'shows' when the schema is called 'Show' ? Where does that naming convention come from? @SandeepPatel Thanks – Retro Sep 21 '19 at 08:23
  • The first argument is the singular name of the collection your model is for. ** Mongoose automatically looks for the plural, lowercased version of your model name. Pls, read this https://mongoosejs.com/docs/models.html. If you want to override the default model you can pass the third parameter as collection name.For example `mongoose.model('ModelName', Schema,collectionName)`; – Sandeep Patel Sep 21 '19 at 08:43

3 Answers3

0

Please see also: https://stackoverflow.com/a/55386123/211827 — when querying dates, use actual dates. When querying ObjectIds use real ObjectIds. Etc. Because your strings are literally the worst possible date format for any form of lexicographical expectation. Specifically: not following the ISO date format form of least specific to most specific (year, month, day) will prevent any form of sorting, range querying, or essentially any of the "most useful" things you can use actual dates for when stored as strings, which is not an appropriate storage format for dates, generally.

"2019/09/21" = 11 bytes. The same date represented using the Julian calendar: 2458748, or a 32-bit integer (4 bytes), no time component. UNIX timestamp would be 64-bit, so 8 bytes, and you'd also have to throw away or ignore the time component within. Even the wrong right way is better than the wrong wrong way. ;)

amcgregor
  • 1,228
  • 12
  • 29
-1

Check-in you Database that there is date formate like '02/03/1995', it can be via saving, you are changing you formate if not then please share your one object of your schema.

This is working properly in my schema.

db.getCollection('users').find({dob:'02/03/1995'})
Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32
  • In "rubber duck debugging" this to my mother (who groks the ObjectId/datetime casting issue quite handily, actually) even she recognized that if you sort those dates, you'll get every date in September for every year grouped together, then every date in October for every year, then… Challenge question this date string instantly poses: {efficiently, without regular expressions} find me all documents between January and March 2019. Good luck. (It's essentially useless for most uses one puts a date to, and wasteful of storage, see my answer.) – amcgregor Jan 01 '20 at 17:00
-1

Check whether your date in db is in iso date or iso string format.
If it is an iso date than you will have to do new Date(09-20-2019).
If its an iso string then you also need to consider the timezone.
Try to find using a between query 09-20-2019 & 09-21-2019.
You should get the data.

Sagar Chaudhary
  • 1,343
  • 7
  • 21
  • `09-20-2019` == `-2030` == Wednesday, December 31st, 1969 at 18:59:57 UTC-0500 (EST). So the code as given is rather badly wrong. Additionally, one _always_ needs to consider timezones. **Storage and transfer in UTC is best practice**, as that "timezone" (which is not really a timezone as such) does not suffer from daylight savings (there are no hours duplicated or missing from years), making a given time or date absolute and unambiguous. – amcgregor Sep 25 '19 at 15:22