Sunday, 4 June 2017

How to set a relation when saving mongoose documents?

I am having trouble inserting a new document into a mongo database using mongoose. I have an async await function that will fetch a lecture record and then see if there is a corresponding response. When I run this function, I can properly see the ids of the lecture and user in the console.log statement but when I look at the lectureResponse, it only has the _id field in it, not the userId or lectureId. (It also has this strange __v field that is set to 0.)

How can I properly establish the user and lecture relationship here when simply setting the field doesn't appear to work?

export default async function lectureResponseFromNames({ lectureId, userId }) {
  try {
    const lecture = await Lecture.findOne({ lectureId });
    const lectureResponse = await LectureResponse.findOne({ lectureId: lecture.id, userId });

    if (lectureResponse !== null) {
      return lectureResponse;
    } else {
      console.log(lecture.id, userId)
      const lectureResponse = await new LectureResponse({
        _id: randomID(17),
        userId: userId,
        lectureId: lecture.id,
      });
      lectureResponse.save();    
    }
  } catch(err) {
    console.log(err);
  }
}



via Coherent

No comments:

Post a Comment