【问题标题】:Confirm collection exists using mongoose使用 mongoose 确认集合存在
【发布时间】:2017-02-02 07:23:43
【问题描述】:

MongoDB 新手,所以我希望我的术语是正确的...

我有一个包含用户集合的数据库。在节点中,我想检查一个字段的值,但是,首先我需要确保该字段存在。

例如,这是我的用户架构:

var mongoose = require('mongoose');
var userSchema = mongoose.Schema({

    local: {
        email        : String,
        password     : String,
    },
    facebook         : {
        id           : String,
        token        : String,
        email        : String,
        name         : String
    }
}

某些用户同时拥有本地和 facebook 文档/字段?而其他人可能有。

如果文档中存在两个字段,我希望确认当前用户文档在两个字段中都有电子邮件值。即

User.local.email & User.facebook.email

如果我尝试直接访问电子邮件字段并且该文档不存在该字段,我会得到:

TypeError: Cannot read property 'email' of undefined

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    试试这个 -

    var localExists = User.local != null;
    var facebookExists = User.facebook != null;
    
    if(localExists && facebookExists){
        // both exist so check if both have email
        var bothHaveEmail = User.local.email != null && User.facebook.email != null;
    }
    else if(localExists){
        // only local exists
    }
    else if (facebookExists){
        // only facebook exists     
    }
    else{
        // nothing exists
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试

      const localEmail = user.local && user.local.email;
      const fbEmail = user.facebook && user.facebook.email;
      

      如果任一设置为undefined,则表示该电子邮件字段不存在

      【讨论】:

        猜你喜欢
        • 2011-11-07
        • 2018-08-11
        • 2011-08-13
        • 2012-11-06
        • 2018-08-21
        • 2019-08-07
        • 2013-02-24
        • 2021-05-21
        • 1970-01-01
        相关资源
        最近更新 更多