1

I am using Node.js, mongoose, mongodb, express and angular. I am saving replies for a survey in a mongoose model. Many people will submit replies for a particular survey. When the first person submits a reply for a survey, I want to create a new document for that survey. When the second, third.... so on people submit replies for the same survey, I want to add array elements only to the replies array in the following schema.

And when the first person submits a reply for a new survey I want to create a new document for the new survey. How can I do this in mongoose?

I found similar question in Mongoose.js: how to implement create or update?. But, here I want to push the new replies to the next array index of replies[] if the _id is found, else create a new document

mongoose model:

 var mongoose = require("mongoose");
 var Schema = mongoose.Schema;

 var MCQReplySchema = new Schema({ 

    _id : String,
    surveyname: String,
    replies :[{
        replierId : String,
        answers : [{
            questionId : String,
            answer : String
        }]  
    }]

    });

 module.exports=mongoose.model('MCQReply',MCQReplySchema);

Saving data to database:

      router.post("/saveMCQAnswer", function(req, res) {

       new MCQReply({

       _id : '123',
        surveyname: 'sample',
        replies :[{
          replierId : 'R001',
          answers : [{
            questionId : 'A001',
            answer : 'answer'
          }]  
        }]

    }).save(function(err, doc){
      if(err) res.json(err);
      else
      req.flash('success_msg', 'User registered to Database');  
      res.redirect("/");

    });

   });
Community
  • 1
  • 1
Kabilesh
  • 1,000
  • 6
  • 22
  • 47
  • `_id` is actually implicit by default and Mongoose tries to create a unique `_id` - See http://mongoosejs.com/docs/guide.html#_id. Is there a specific reason you want to specify the ID yourself? – GPX Mar 08 '17 at 06:38
  • Have you seen this http://stackoverflow.com/a/13338758/6048928 – RaR Mar 08 '17 at 06:46
  • 1
    Possible duplicate of [Mongoose.js: how to implement create or update?](http://stackoverflow.com/questions/13337685/mongoose-js-how-to-implement-create-or-update) – RaR Mar 08 '17 at 06:47
  • yes GPX. I am passing the surveyId to _id. Survey was already created. The _id of Created Survey and Reply for Survey must be same – Kabilesh Mar 08 '17 at 07:19

1 Answers1

1

pseudo untested code.

    MCQReply.findOne({_id : the id}, function(err,doc){
        if(err) console.log(err);
        // if the survey isn't there `doc` will be null then do your save
        if(!doc){
          new MCQReply({

           _id : '123',
            surveyname: 'sample',
            replies :[{
              replierId : 'R001',
              answers : [{
                questionId : 'A001',
                answer : 'answer'
              }]  
            }]

            }).save(function(err, doc){
              if(err) res.json(err);
              else
              req.flash('success_msg', 'User registered to Database');  
              res.redirect("/");

            });                 
        }else(doc){
            //you get mongoose document
            doc.replies.push({replierId : "R001", answer : [{questionId : "A001" ... whatever else you want}]})

            //dont forget to save
            doc.save(do error check)
        }


    })

Don't know if this will work but if your having trouble just saving the _id try this for Schema()

var MCQReplySchema = new Schema({ 

    _id : String,
    surveyname: String,
    replies :[{
        replierId : String,
        answers : [{
            questionId : String,
            answer : String
        }]  
    }]

    }, {strict : false});

if {strict :false} doesn't work

try {strict : false, _id :false} or just _id : false

jack blank
  • 5,073
  • 7
  • 41
  • 73
  • Thanks for your answer. But, I get some problems. doc.replies.push({replierId : "R002", answer : [{questionId : "A002"},{answer : "A001"}]}); I modified your code. For the first most reply it did not save a replierId and questionId. For the second reply again no replierId and nothing inside answer[]. Can you help me with this? – Kabilesh Mar 08 '17 at 09:13
  • The schema is in the above question. I uploaded a screen shot of the schema in Robomongo. It will be visible if accepted. – Kabilesh Mar 08 '17 at 13:31
  • What if you add strict :false to the schema option. any changes. new `Schema({}, strict :fasle)` – jack blank Mar 08 '17 at 14:48
  • Ok edited. strict is for saving stuff that is not in the `schema` so maybe you have that type of issue. and _id false I think helps with not display the _id maybe it will help if you use your own `_id` or tells mongo not to generate own `_id` – jack blank Mar 08 '17 at 15:21