简体   繁体   中英

Querying through data in mongoose database

I am currently trying to query through the data so that it only returns items with an id of bWYqm6-Oo(I only have 1 item as of now) between two specific dates 2019-09-19 and 2019-09-22. In this case it should only return the first 3 items in the database. I came up with a query but it only returns an empty array. Would somebody know how to solve this? Thank you in advance.

var findBy = {
    _id : bWYqm6-Oo,
    exercises : [
      {
        date: {
          $gte: 2019-09-19,
          $lt: 2019-09-22
        }
      }
    ]
  }
  UserModel.find(findBy).limit(5).exec((err, data) => {
      (err) ? res.json({"error" : "problem searching for exercises: " + err}) :  res.json(data);      
  });

My database looks like this:

{
    _id: "bWYqm6-Oo",
    user: "rommy",
    exersises: [
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-20T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-21T00:00:00.000Z",
        description: "pushup",
        duration: "22",
        _id: "YtfsJLOXb"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-20T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-24T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        }
    ],
    __v: 9
}

Here is where I call my files in the server.js file:

A few things:

The field _id on a document is always unique in mongo, therefore in your query

var findBy = {
    _id : bWYqm6-Oo,
    exercises : [
      {
        date: {
          $gte: 2019-09-22,
          $lt: 2019-09-22
        }
      }
    ]
  }

This part is redundant

exercises : [
      {
        date: {
          $gte: 2019-09-22,
          $lt: 2019-09-22
        }
      }
    ]

because there will only be one document with the _id of 'bWYqm6-Oo'

If you want to query using date range you can do something like this:

var query = {
  'exercises.date': {$gte: '2019-09-22', $lt: '2019-09-22'}
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM