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