【问题标题】:Find subdocument object in another db在另一个数据库中查找子文档对象
【发布时间】:2020-12-05 09:16:40
【问题描述】:

我正在尝试检查与会者的每封电子邮件,看看他们是否是注册用户。如果没有,我会给他们发一封电子邮件(尚未编码,稍后再做)。

这是事件和用户架构:

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
});
     
const Event = new Schema({
    title: {
        type: String,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users'
    },
    attendees:[
     {email: {
        type: String,
        required: true
     },
     name: {
        type: String,
        required: true
     },
     status: {
     type: String
     }}
   ]
}); 

router.post('/', auth, async (req, res) => {
  const {title,
    attendees
  } = req.body

  if (!title) {
    return res.status(400).json({ msg: 'Please enter a title' });
  }

  try{  
    const newEvent = new Event({
        title,
        user: req.user.id,
        attendees:  attendees.map(x => ({
          email: x.email,
          name: x.name,
          status: x.status,
        })),
    });

const attendeeExists = await User.findOne({"attendees.email":email});
if (!attendeeExists) throw Error("User doesn't exist. Send email");

最后两行给我一个错误:未定义电子邮件。 不知道我错过了什么。

这适用于用户路线:

const user = await User.findOne({ email });

【问题讨论】:

  • 看不到您发布的代码中定义的email,因此出现错误。这个email 来自哪里?请分享更多细节。
  • 添加了事件和用户的架构。
  • 所以您想测试是否有任何参加者的电子邮件存在于 db 中,它来自 req.body 中的 attendees 变量?
  • 没错!我想用用户电子邮件检查与会者电子邮件。

标签: arrays mongodb mongoose


【解决方案1】:

感谢@ambianBeing,您的解决方案帮助我获得了一个可行的模型。

const email = attendees.map((a) => a.email);
const attendeesFound = await User.find({email});

【讨论】:

    【解决方案2】:

    要检查找到的任何与会者的电子邮件,可以使用 .find()$in,这将返回找到的具有任何电子邮件 ID 的用户。

    /*collect all emails to test*/
    const emails = attendees.map((a) => a.email);
    const attendeesFound = await User.find({ "email": { $in: emails } });
    

    另一个 Mongoose 语法与上面做同样的事情:

    /*collect all emails to test*/
    const emails = attendees.map((a) => a.email);
    const attendeesFound = await User.find({}).where("email").in(emails);
    

    【讨论】:

    • 运行测试时,“attendeesFound”返回一个空数组,即使我发送的是用户数据库中的电子邮件。 “电子邮件”正在正确返回来自输入的电子邮件列表。
    • @morethan1 请立即查看!已根据我之前错过的Userschema 更新了查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多