I am developing an online survey application based on React, NodeJS, Express, MongoDB and Mongoose. I face this issue when I wanted to post a request (via a form submission) to the MongoDB via Mongoose and I always get error message "Creating answer failed, please try again." with my code to recognize it is related to error happened with DB. I can see the request body is created actually in payload of request; however, the document is not created in the MongoDB. Please refer to the related code as below.
https://codesandbox.io/s/sharp-glitter-885pg?file=/src/backend/model/text-question.js
CodePudding user response:
Try to push
the _id
of the createdAnswer
instead of the whole object after its creation in the text-controller.js
file:
...
const sess = await mongoose.startSession();
sess.startTransaction();
await createdAnswer.save({ session: sess });
// Add createdAnswer id to the specific user
user.answers.push(createdAnswer._id); // <- CHANGE THIS LINE
await user.save({ session: sess });
await sess.commitTransaction();
...