在另一个数据库中查找子文档对象 [英] Find subdocument object in another db

查看:73
本文介绍了在另一个数据库中查找子文档对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to check each email of attendees and see if they are a registered user. If not, I will send them an email (not yet coded, will do later).

以下是事件和用户模式:

Here's the event and user schema:

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");

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

The last two lines are giving me an error: email is not defined. Not sure what I'm missing.

这适用于用户路由:

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


推荐答案

找到与会者的电子邮件,其中 .find() $ in 可以使用,它将返回使用任何电子邮件ID找到的用户。

For checking any of the attendee's email found, .find() with $in can be used which'll return the users found with any of the email ids.

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

另一种Mongoose语法也与上述相同:

Another Mongoose syntax wihich does the same thing as above:

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

这篇关于在另一个数据库中查找子文档对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆