Node.js 使用mongoose确认集合存在

Node.js 使用mongoose确认集合存在,node.js,mongodb,Node.js,Mongodb,MongoDB新手,所以我希望术语正确 我有一个包含用户集合的数据库。在node中,我想检查字段的值,但是,首先我需要确保字段存在 例如,下面是我的用户模式: var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ local: { email : String, password : String, }, facebook

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

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

例如,下面是我的用户模式:

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

    local: {
        email        : String,
        password     : String,
    },
    facebook         : {
        id           : String,
        token        : String,
        email        : String,
        name         : String
    }
}
有些用户同时拥有本地和facebook文档/字段?而其他人可能有两种情况

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

User.local.email & User.facebook.email
如果我试图直接访问“电子邮件”字段,但该字段不存在,我会得到:

TypeError: Cannot read property 'email' of undefined
试试这个-

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
}
你可以试试

const localEmail = user.local && user.local.email;
const fbEmail = user.facebook && user.facebook.email;
如果其中一个设置为
undefined
,则表示该电子邮件字段不存在