简体   繁体   中英

How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?

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("/");

    });

   });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM