Znajdź obiekt dokumentu podrzędnego w innej bazie danych

Aug 15 2020

Próbuję sprawdzić każdy e-mail uczestników i sprawdzić, czy są zarejestrowanymi użytkownikami. Jeśli nie, wyślę im e-mail (jeszcze nie zakodowany, zrobię później).

Oto schemat zdarzenia i użytkownika:

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

W ostatnich dwóch wierszach pojawia się błąd: adres e-mail nie jest zdefiniowany. Nie wiem, czego mi brakuje.

Działa to w przypadku tras użytkowników:

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

Odpowiedzi

morethan1 Aug 18 2020 at 15:09

Dzięki @ambianBeing, Twoje rozwiązanie pomogło mi uzyskać działający model.

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

Dla sprawdzenia któregokolwiek uczestnika E-mail znaleziony, .find()ze $inmożna stosować which'll przywrócić użytkownikom znaleźć z każdym z identyfikatorów e-mail.

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

Kolejna składnia Mongoose, która robi to samo, co powyżej:

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