[英]Querying with mongoose of dates type
I am trying to convert parameters in request body to mongoose query to get response of the data in mongodb
whose "lastUpdated"
is greater than "2018-04-03T08:01:19.269Z"
. 我试图将请求正文中的参数转换为猫鼬查询,以获取
mongodb
"lastUpdated"
大于"2018-04-03T08:01:19.269Z"
的数据的响应。 I post the request through postman with parameters in body 我通过邮递员在正文中使用参数发布请求
{
"checkedOut" : false,
"valid" : false,
"language" : "en",
"lastUpdated" : "2018-04-03T08:01:19.269Z",
"__v" : 0
}
the response works good in responding the data whoes "lastUpdated"
is equal to "2018-04-03T08:01:19.269Z"
. 该响应在响应数据whoes
"lastUpdated"
等于"2018-04-03T08:01:19.269Z"
。 I write a function in my code: 我在代码中编写了一个函数:
for (const key in params) {
if (key === "lastUpdated") {
params[key] = {$gte : value};
}
}
return params
So I got a new query: 所以我得到了一个新的查询:
{ checkedOut: false,
valid: false,
language: 'en',
lastUpdated: { '$gte': '2018-04-03T08:01:19.269Z' },
__v: 0
}
But it still does not work...... please help ...... 但这仍然行不通......请帮助......
In your case value
is a string so you should just convert it to date via: 在您的情况下,
value
是一个字符串,因此您应该通过以下方式将其转换为日期 :
for (const key in params) {
if (key === "lastUpdated") {
params[key] = {$gte : new Date(value)};
}
}
return params
This way mongoDB would compare dates with valid date
. 这样,mongoDB会将
dates with valid date
进行比较。
Using query builder will solve this question: 使用查询生成器将解决此问题:
const query = model.find();
let datequery = {};
let otherquery = {};
for (const key in params) {
if (key === "lastUpdated") {
datequery[key] = params[key];
} else {
otherquery[key] = params[key];
}
}
console.log(otherquery,datequery);
query.where(transformCondition(otherquery));
query.where('lastUpdated').gte(datequery['lastUpdated']);
return query;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.