2

I have create one schema to store questions and answers :

var questionSchema = mongoose.Schema({
    questions : {type: String},
    details   : {type: String},
    tags      : {type: String},
    answer    : [{String}],
 });

In this i want to store multiple answers for one question but i have one question page and different page for answer my requirement is to store multiple answers in one question any suggestions.

Thanks,

Deepak

2 Answers 2

1

If you want to store an array of string, the correct syntax is the following :

answer: [String]

If answer is an array of objects, you can do something like that :

var questionSchema = mongoose.Schema({
  questions :{type: String},
  details   :{ type: String},
  tags      :{type: String},
  answer    :[{
    answer: String,
    tags: [String]
  }],
});

If a answer is something that you've got in your DB, you can create a schema and reference it in your question schema :

var Answer = new Schema({
  text: String,
  user_id: Number
});

var questionSchema = mongoose.Schema({
  questions :{type: String},
  details   :{ type: String},
  tags      :{type: String},
  answer    :[Answer],
});

Hope it helps,
Best regards

Sign up to request clarification or add additional context in comments.

9 Comments

Hey, for this i have to write separate api for question and answer schema?
You do as you want, the first solution is the easiest : just store an array of strings. But if the answers are related to a user, and if you want to add a vote system later you might want to store more information about the answers. To do so, it's a good solution to represent these answers as a mongodb schema. Then you will be able to perform operations on answers without having to query all questions
Hey, Its not working for me is there any way to do this
What is not working ? Which solution are you trying to implement ?
i am trying second solution, would you please give some node api example to do this
|
0

HI can you try like this

var questionSchema = mongoose.Schema({
    questions :{type: String},
    details   :{ type: String},
    tags      :{type: String},
    answer    :[{
                 text: String,
                }]
 });

Also refer the doc

http://mongoosejs.com/docs/schematypes.html#schematypes

Reference link: mongoose: Referencing schema in properties or arrays

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.