【问题标题】:Check if a document exists in mongoose (Node.js)检查文件是否存在于猫鼬(Node.js)中
【发布时间】:2013-11-09 04:18:18
【问题描述】:

我已经看到了许多在 mongoDB 中查找文档的方法,这样不会影响性能,即您并没有真正检索到文档;相反,如果文档存在与否,您只需检索 1 或 0 的计数。

在 mongoDB 中,可能可以这样做:

db.<collection>.find(...).limit(1).size()

在猫鼬中,你要么有回调,要么没有。但在这两种情况下,您都是在检索条目而不是检查计数。我只是想要一种方法来检查文件是否存在于猫鼬中——我不想要文件本身。

编辑:现在摆弄异步 API,我有以下代码:

for (var i = 0; i < deamons.length; i++){
    var deamon = deamons[i]; // get the deamon from the parsed XML source
    deamon = createDeamonDocument(deamon); // create a PSDeamon type document
    PSDeamon.count({deamonId: deamon.deamonId}, function(error, count){ // check if the document exists
        if (!error){
            if (count == 0){
                console.log('saving ' + deamon.deamonName);
                deamon.save() // save
            }else{
                console.log('found ' + deamon.leagueName);
            }
        }
    })
}

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

我发现这种方式更简单。

let docExists = await Model.exists({key: value});
console.log(docExists);

否则,如果你在函数中使用它,请确保函数是async

let docHandler = async () => {
   let docExists = await Model.exists({key: value});
   console.log(docExists);
};

【讨论】:

    【解决方案2】:

    您必须阅读有关 javascript 范围的信息。无论如何尝试以下代码,

    for (var i = 0; i < deamons.length; i++) {
        (function(d) {
            var deamon = d
            // create a PSDeamon type document
            PSDeamon.count({
                deamonId : deamon.deamonId
            }, function(error, count) {// check if the document exists
                if (!error) {
                    if (count == 0) {
                        console.log('saving ' + deamon.deamonName);
                        // get the deamon from the parsed XML source
                        deamon = createDeamonDocument(deamon);
                        deamon.save() // save
                    } else {
                        console.log('found ' + deamon.leagueName);
                    }
                }
            })
        })(deamons[i]);
    }
    

    注意:由于它包含一些数据库操作,我没有测试。

    【讨论】:

    • 谢谢。现在,我刚刚做了:deamons.forEach(function(deamon){。这行得通,但我想知道这是否是一个好方法?谢谢,我会阅读 javascript 范围。
    • @flippex,您也可以使用“forEach”。当然,“forEach”也是非常直接的好方法
    • 好的,太棒了。谢谢。
    【解决方案3】:

    您可以使用count,它不会检索条目。它依赖于 mongoDB 的 count operation 其中:

    Counts the number of documents in a collection. 
    Returns a document that contains this count and as well as the command status. 
    

    【讨论】:

    • 这是异步调用还是同步调用,因为我需要将其返回给其他函数?
    • @flippex17 这是一个异步调用,你需要链接你的调用。见stackoverflow.com/questions/17181248/…
    • 我刚刚添加了一些代码,如果您能帮助解决问题,我将不胜感激。 (我对javascriptNode.js 真的很陌生)。谢谢!
    • 看起来forEach 是要走的路?
    猜你喜欢
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2013-09-19
    • 2013-06-04
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多