繁体   English   中英

检查 mongoose (Node.js) 中是否存在文档

[英]Check if a document exists in mongoose (Node.js)

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

在 mongoDB 中,你可能会这样做:

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

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

编辑:现在摆弄异步 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);
            }
        }
    })
}

您必须阅读有关 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]);
}

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

您可以使用count ,它不会检索条目。 它依赖于 mongoDB 的计数操作

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

我发现这种方式更简单。

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

否则,如果您在函数内使用它,请确保该函数是async

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

暂无
暂无

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

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