Найти объект вложенного документа в другой базе данных

Aug 15 2020

Я пытаюсь проверить каждую электронную почту участников и посмотреть, являются ли они зарегистрированным пользователем. Если нет, я отправлю им электронное письмо (еще не закодировано, сделаю позже).

Вот схема события и пользователя:

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

Ответы

morethan1 Aug 18 2020 at 15:09

Спасибо @ambianBeing, ваше решение помогло мне получить рабочую модель.

const email = attendees.map((a) => a.email);
const attendeesFound = await User.find({email});
ambianBeing Aug 17 2020 at 22:15

Для проверки любого найденного адреса электронной почты участника можно использовать .find()with $in, который вернет пользователей, найденных с любым из идентификаторов электронной почты.

/*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);