我一直在使用标准的mongodb驱动程序3.2.6版以快速方式编写应用程序。我需要对我的数据库进行查询,我想进行5年查询并逐年计数。当我静态编写代码时,它可以毫无问题地工作,如果我将相同的确切值放入变量中并将其插入查询中,则会拒绝工作。
如果这很明显我错过了,我深表歉意,但是我找不到解决方法。感谢所有尝试提供帮助的人:)
此代码有效。输出是波纹管
router.get("/test", (req, res) => {
result = {
title : "Somethings through time",
data : []
}
for(let i = 4;i<9;i++) {
const query = `/2014/`;
db.getDB().collection("somethings").find({"date_of_something": /2014/}).count().then(numOf => {
console.log(query +"\n"+numOf);
});
}
res.json({
success: false
});
});
输出:
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
此代码无效。
router.get("/test", (req, res) => {
result = {
title : "Somethings through time",
data : []
}
for(let i = 4;i<9;i++) {
const query = `/2014/`;
db.getDB().collection("somethings").find({"date_of_something": query}).count().then(numOf => {
console.log(query +"\n"+numOf);
});
}
res.json({
success: false
});
});
输出:
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0
答案 0 :(得分:1)
这是一个正则表达式
/2014/
但是这个带有反勾号的字符串只是一个普通的字符串
`/2014/`
要从字符串创建新的正则表达式,您可以像这样
const query = new RegExp(`201${i}`)
在MongoDB中使用正则表达式进行匹配时,您应该使用$regex
运算符
{"date_of_something": {$regex: query}}
还值得注意的是,您在不等待查询完成就返回结果res.json
的情况下,应await
进行查询,而请求处理程序应为async
router.get("/test", async (req, res) => {
...
const numOf = await db.getDB().collection("somethings")
.find({"date_of_something": {$regex: query}}).count();
console.log(query +"\n"+numOf);
})