Başka bir veritabanında alt belge nesnesini bulun

Aug 15 2020

Katılımcıların her e-postasını kontrol etmeye ve kayıtlı bir kullanıcı olup olmadıklarını görmeye çalışıyorum. Değilse, onlara bir e-posta göndereceğim (henüz kodlanmamış, daha sonra yapacağım).

İşte olay ve kullanıcı şeması:

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

Son iki satır bana bir hata veriyor: e-posta tanımlanmadı. Ne kaçırdığımdan emin değilim.

Bu, kullanıcı rotalarında çalışır:

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

Yanıtlar

morethan1 Aug 18 2020 at 15:09

Teşekkürler @ambianBeing, çözümünüz çalışan bir model edinmeme yardımcı oldu.

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

, Katılımcının e-posta, bulan herhangi denetimi için .find()olan $inkullanıcı döndürmek which'll kullanılabilecek e-posta kimlikleri herhangi biriyle bulundu.

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

Yukarıdaki ile aynı şeyi yapan başka bir Mongoose sözdizimi:

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