简体   繁体   English

Mongoose 在查找之前应用 getter

[英]Mongoose apply getters before find

I have inherited a Mongo collection that stores Dates as strings eg "2020-11-18" rather than as BSON Dates.我继承了一个 Mongo 集合,该集合将日期存储为字符串,例如“2020-11-18”而不是 BSON 日期。 I have a getter that converts this string to a js Date but I would like to query the collection by date range as follows:我有一个可以将此字符串转换为 js 日期的 getter,但我想按日期范围查询集合,如下所示:

const Things = mongoose.Model('Thing',
    {
        date: { type: String, get v => new Date(v) }
    }, 
    {
        toJSON: { getters: true },
        toObject: { getters: true },
    }
)

Things.find({ date: { $gt: new Date("2020-11-17"), $lt: new Date("2020-11-19") } })

It seems that the getter is not applied to documents before the find query is executed.在执行查找查询之前,似乎没有将 getter 应用于文档。 Is there any way to do this?有没有办法做到这一点?

As mentioned in this docs :如本文档所述

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.干将允许你把它从原始MongoDB的文档,你看到的价值传播转换数据的代表性

So your date getter will run just after the execution of the find() method.因此,您的date将在find()方法执行后立即运行。 Otherwise, how the date's representation will be changed before finding the date itself !否则,在找到日期本身之前,日期的表示将如何改变!

In another words:换句话说:

Things.find({ date: { $gt: new Date("2020-11-17"), $lt: new Date("2020-11-19") } })
    // getter will run here
    .then((queryResults) =>{
      
    })

Dates in that format have the fortunate property that their lexicographic sort order is the same as their chronological order.这种格式的日期有一个幸运的特性,即它们的字典排序顺序与它们的时间顺序相同。

That means that you can query them as strings and match the documents you would expect.这意味着您可以将它们作为字符串查询并匹配您期望的文档。

For example, in a collection containing例如,在一个包含

[
    {"date": "2020-11-16"},
    {"date": "2020-11-17"},
    {"date": "2020-11-18"},
    {"date": "2020-11-19"}
]

The query查询

db.Things.find({"date": {$gte: "2020-11-17", $lt: "2020-11-19"}})

Returns {"date": "2020-11-17"} and {"date": "2020-11-18"} , as expected.正如预期的那样,返回{"date": "2020-11-17"}{"date": "2020-11-18"}

Playground操场

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

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