简体   繁体   English

猫鼬从html datepicker找到2个日期之间的结果

[英]Mongoose find results between 2 dates from html datepicker

I have the following sub-documents : 我有以下子文档:

{
 id: 1,
 date:2019-04-01 00:21:19.000
 },
{
 id: 2, 
 date:2019-03-31 00:21:19.000
} ...
Document schema is :
const barEventSchema = new Schema({
id: {
    type: Number,
    unique: true,
    required: true
},
raw: { type: String },
date: { type: Date },
type: { type: String },

})

const FooSchema = new Schema({
   bar: [barEventSchema]
})

I want to do a query based on a date range picked from html input, which has values like 2019-04-01 , 2019-03-31 . 我想根据从HTML输入,具有象值挑选日期范围做了查询2019-04-012019-03-31 So on serverside, I want to do something like: 因此,在服务器端,我想执行以下操作:

//@star_date = 2019-04-01, @end_date = 2019-04-01
Foo.findOne('bar.date' : {$lte : start_date, $gte: end_date})

However, this returns all the documents. 但是,这将返回所有文档。

All documents having any subdocument with date between start and end date range can be retrieved using: 可以使用以下方法检索所有子文档的日期在开始和结束日期范围之间的子文档:

const conditions = {
  'bar': {
    $elemMatch: {
      'date': {
        $gte: new Date(start_date), 
        $lte: new Date(end_date)
      }
    }
  }
}

Foo.find(conditions)

This will return all the documents where there is at least a subdocument having its date between the range specified in condition . 如果存在至少一个子文档,且其日期在condition指定的范围之间,则将返回所有文档。 The $elemMatch operator is used to effect this condition on the date field of the bar subdocument. $elemMatch运算符用于在bar子文档的date字段上实现此条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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