MongoDB 检查属性是否存在(以及子属性)

标签 mongodb meteor

是否有更常规的方法来检查 MongoDB 文档中是否存在属性和子属性?

现在我这样做是为了确保当其中一个属性或整个文档不存在时它不会出错。

//Check to see if the document exists
if(Donate.findOne({'debit.id': debitID})) { 
    //Check to see if the document has the property "credit"
    if(Donate.findOne({'debit.id': debitID}).credit){ 
        //Check to see if the object credit has the property sent
        if(!Donate.findOne({'debit.id': debitID}).credit.sent){
            doSomething();
        }
    }
}

!Donate.findOne({'debit.id': debitID}).credit.sent是看sent是否设置为true。如果是,我不想执行 doSomething();

最佳答案

试试这个:

Donate.findOne({'debit.id': debitId, 'credit.sent': {$exists: true}});

虽然我不完全确定您要做什么,因为您的代码似乎正在检查属性“credit”和“credit.sent”是否存在。如果这就是您要查找的内容,则只需将上面的 $exists 条目更改为 false

关于MongoDB 检查属性是否存在(以及子属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412318/

相关文章:

ruby-on-rails - Mongo::Error::UnsupportedFeatures(位于 (localhost:27017) 的服务器报告有线版本 (2),但此版本的 Ruby 驱动程序至少需要 (6)。)

meteor - 如何将 ngrok 与 Google Oauth 结合使用?

meteor - 一开始如何在客户端和服务器中使用环境变量

node.js - 如何在 OpenShift Gear 中升级 Node.js

meteor - 从 currentView 获取 jQuery 元素

javascript - 如何发布 meteor 集合中的所有记录......除了一两个

ruby - 如何查询 Mongoid 正则表达式字段?

windows - 无法在 Windows 上将持久文件夹添加到 bitnami/mongodb

mongodb - 使用 MongoDB 进行 DDD

mongodb - wiredtiger内存使用量增长