Home > Net >  How to generate an objectId for each element when saving an array in mongoose/node?
How to generate an objectId for each element when saving an array in mongoose/node?

Time:12-26

I am building an app to make simple surveys, and I am using mongoose. I setup a single entity to define surveys, and this entity includes questions and answers

const mongoose = require("mongoose");
const {User} = require("./User");

const SurveySchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    title: {
        type: String,
        minLength: 5,
        maxlength: 100,
        required: true
    },
    // other fields///
    questions: [{
        question: {
            type: String,
            minLength: 10,
            maxlength: 200,
            required: true
        },
        answers: [{
            type: String,
            minLength: 10,
            maxlength: 100,
            required: false
        }],
    }],
}, {timestamps: true} );

module.exports.Survey = mongoose.models.Survey || mongoose.model('Survey', SurveySchema);

when I need to add a question to a survey, I am doing this (answers is just an array of strings)

let survey = await surveyManager.getSurvey(surveyId);
let newQuestion = {
  question: question,
  answers: answers
};
survey.questions.push(newQuestion);
await survey.save();
return survey;

and this is my new question as seen quering mongodb from the command line

"questions" : [
  {
    "question" : "this is a question?",
    "answers" : [
          "answer number 1",
          "answer number 2",
          "answer number 3"
    ],
    "_id" : ObjectId("63a89d2e101149d7958e0f78")
  }
],

as you can see, an object id is assigned to each question, which is fine. So my question is, how can I assign an object id to each answer as well? I'd need it to refer to then form another collection.

CodePudding user response:

I suppose you could declare your answers like so and this will automatically assign an _id to them:

const SurveySchema = mongoose.Schema({
 ...
 ...
    questions: [{
        question: {
            type: String,
            minLength: 10,
            maxlength: 200,
            required: true
        },
        answers: [{
            type: new mongoose.Schema({
                answer_text: {
                    type: String,
                    minLength: 10,
                    maxlength: 100,
                    required: false
                }
            })
        }]
    }],
});

CodePudding user response:

You can just set the answers to be an object, and Mongoose will add a new _id to each item in the array:

questions: [{
  question: {
    type: String,
    minLength: 10,
    maxlength: 200,
    required: true
  },
  answers: [{
    answer: {
      type: String,
      minLength: 10,
      maxlength: 100,
      required: false
    }
  }],
}],
  • Related