MongoDB动态查询与javascript,工作静态,而不是变量



我一直在使用标准的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
这是一个

正则表达式

/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);
})

最新更新