使用_Id的电子邮件更新集合作为唯一ID

时间:2017-09-06 12:08:43

标签: javascript mongodb meteor

我有2个收集表,它们只共享电子邮件作为这两个表的唯一ID。第一个是Meteor.users()SchoolStudents。我想根据用户的电子邮件更新SchoolStudents集合。虽然我已使用_id成功更新,但更新无法使用电子邮件作为Id。什么是更好的方法?

在此,它返回了成功反馈,但未对记录进行更新。 Bert.alert('Record updated successfully', 'success', 'growl-top-right');

客户代码:

let user = Meteor.user();
let studentemail = user && user.emails && user.emails[0].address;
   if (studentemail) {
        console.log(studentemail);
        Meteor.call('UpdateUser', studentemail, function (error, response) {
        if (error) {
          Bert.alert(error.reason, 'danger', 'growl-top-right');
          return false;
        } else {
            Bert.alert('Record updated successfully', 'success', 'growl-top-right');
         }
      })
  }

服务器方法

SchoolStudents.update({useremail: studentemail}, {$set: {'status.active': true, 'status.activedate': new Date()}});

这是来自 SchoolStudents 集合的示例文档:

{
    "_id" : "xgxZJFRkXGhHmHupY",
    "firstname" : "Kehinde",
    "lastname" : "Adeoya",
    "middlename" : "Adekusibe",
    "username" : "ken10ward",
    "password" : "PvyLwY9d",
    "useremail" : "kadeoya@appzonegroup.com",
    "studentclass" : "ss8",
    "dateofbirth" : "9-Mar-00",
    "gender" : "f",
    "ethinicity" : "black",
    "mobile" : "8023472442",
    "address" : "7 Abrahamoivc",
    "city" : "bolson",
    "lg" : "loveland",
    "state" : "ekiti",
    "country" : "Ukraine",
    "registra" : "kadeoya",
    "status" : {
        "active" : false,
        "activedate" : null
    },
    "userId" : "n5rqFSHbhm7zqADyB",
    "createdAt" : ISODate("2017-09-05T18:45:14.877Z"),
    "friendlySlugs" : {
        "slug" : {
            "base" : "kehinde-adeoya",
            "index" : 5
        }
    },
    "slug" : "kehinde-adeoya-5"
}

这是服务器更新代码:

UpdateUser: function (studentemail) {
    check(studentemail, String);
    if (!Meteor.userId()) {
        Meteor.Error('Not authorized');
        return false;
    } else {
        SchoolStudents.update({useremail: studentemail}, {status: {active: true, activedate: new Date()}}, { upsert: true });
    }
}

1 个答案:

答案 0 :(得分:-1)

正如您所指出的那样,您正在使用user && user.emails && user.emails[0].address构建错误的方式。

我建议您使用此模板执行以下操作:

let studentemail;
try {
  studentemail = user.emails[0].address.valueOf();
} catch (e) {
  studentemail = null;
}
if (studentemail != null) {
  ...
}

通过这种方式,您可以省略多项检查,例如user != nulluser.emails != null以及user.emails.length > 0等,并且可以保证在studentemail变量中您将获得 null 用户电子邮件地址。

已添加:用户电子邮件地址可能undefined,这就是您需要!= null检查(非严格)的原因。如果变量为falseundefined,则为null