简体   繁体   English

Mongoose/MongoDB 正则表达式使用变量查找查询

[英]Mongoose/MongoDB regex find query using variable

I'm trying to perform a find query in mongoDB (using the mongoose framework with nodejs and express) using a regex expression based on a variable.我正在尝试使用基于变量的正则表达式在 mongoDB 中执行查找查询(使用带有 nodejs 和 express 的猫鼬框架)。 I'm partially able to query correctly using a static string hard-coded into the code but I need to perform the query using a variable who's value is constantly changing.我部分能够使用硬编码到代码中的静态字符串正确查询,但我需要使用值不断变化的变量来执行查询。

The query uses three fields (author, date and updated date) and should go through all documents in a scheme and find all documents where 'date' or 'updated date' is like the variable currentDate (always formatted as YYYY-mm-dd) and where author is authorname.该查询使用三个字段(作者、日期和更新日期),并且应该遍历方案中的所有文档,并找到“日期”或“更新日期”与变量 currentDate 类似的所有文档(始终格式为 YYYY-mm-dd)哪里作者是作者姓名。

The main issue is that mongoDB stores the dates with ISO format.主要问题是 mongoDB 以 ISO 格式存储日期。 On execution the string variable (currentDate (YYYY-mm-dd)) is formatted to ISO which leads it to only "hit" documents with time 00:00.000Z as ISO formats 2015-09-17 to be 2015-09-17 00:00:00.000Z (not taking timezone into consideration).在执行时,字符串变量 (currentDate (YYYY-mm-dd)) 被格式化为 ISO,这导致它只“命中”时间为 00:00.000Z 的文档,因为 ISO 格式 2015-09-17 为 2015-09-17 00 :00:00.000Z(不考虑时区)。

The query:查询:

var currentDate = yyyy-mm-dd;

Scheme.find({$and:[{'local.author': author},
   {$or: [{'local.date': new RegExp(currentDate)}, 
          {'local.updated_date':new RegExp(currentDate)}]}]}

I've also tried with the $gte and $lte variables (where $gte = date today and &lte = date tomorrow (00:00)) but I couldn't get it to work, I met the wall trying to perform the regex.我也尝试过 $gte 和 $lte 变量(其中 $gte = 今天的日期和 &lte = 明天的日期(00:00))但我无法让它工作,我遇到了试图执行正则表达式的墙.

I hope there is a brilliant regex expert out there who can help, thank you!我希望有一位出色的正则表达式专家可以提供帮助,谢谢! :) :)

I figured it out without all the complexity.我想通了它没有所有的复杂性。

var tomorrow = new Date();
var today = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0,0,0,0);
today.setHours(0,0,0,0);

Scheme.find({$and:[{'local.author': author},{$or: [{'local.date': { $gt: today, $lt: tomorrow } },{'local.updated_date':{ $gte: today, $lt: tomorrow }}]}]}

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

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