Reputation: 3
I have a MEAN application and I am allowing users to upload a CSV containing multiple Event rows. After praising the CSV I have a list of Event objects and I can insert the records using mongoose insertMany. I have an Event and Attendee schema like this (simplified for this question).
var EventSchema = new mongoose.Schema({
name: String,
date: Date,
location: String,
speaker: { type: ObjectId, ref: 'Attendee' },
});
var AttendeeSchema = new mongoose.Schema({
firstname: String,
email: {type: String, unique : true},
speaker: Boolean,
});
My issue is when users are uploading the CSV they will only know the email address of the speaker but not the ObjectId. This email will always be unique. While performing an Event.insertMany() is there a way to do a Attendee.findOne on the email and populate the speaker field with an ObjectId ref to an Attendee on each Event as they are inserted.
Upvotes: 0
Views: 1852
Reputation: 831
I think you must do it sequentially:
let email; //you know this email
let events;// prepared events data but without speaker id
Attendee.findOne({email: email}).then(result=>{
events.forEach(event=>event.speaker = result._id);
return events:
})
.then(events=>{
return Event.insertMany(events);
})
.then(results=>{
/*something results handle*/
})
.catch(err=>{
throw err;
})
Upvotes: 0