mongodb - adding multiple same documents using addtoset command in mongoose -
my schema
var userquizschema = mongoose.schema({ uid:{type:objectid,required: true,index:true}, answer:[{content:string, qid:objectid ,time:date }], });
in schema, 'uid' represents user identifier, while 'answer' array stores answers student had answered. in each answer, qid relates question id, , 'content' student's real answer, 'time' modified time stamp answer.
here use mongoose upsert new answers array
function updateanswer(uid,question_id,answer,callback){ var options = { new: false }; var quiz_id = mongoose.types.objectid(quiz_id); var qid = mongoose.types.objectid(question_id); userquizmodel.findoneandupdate({'uid':uid},{'$addtoset':{'answer':{'qid':qid, 'content':answer} } },options,function(err,ref){ if(err) { console.log('update '.red,err); callback(err, null); }else{ console.log('update '.green+ref); callback(null,ref); } }) }
in common sense, using addtoset command, element in answer array should unique, in example, answer array have multiple same embedded documents except each embedded document has 1 unique ojbectid _id
such
answer: [ { qid: 5175aecf0e5b061414000001, _id: 518a5e5895fc9ddc1e000003 }, { qid: 5175aecf0e5b061414000001, _id: 518a5e5f95fc9ddc1e000004 } ] }
you see qid of 2 embedded documents same, _id different.
why there additional _id, don't put schema design ??
you can disable _id
in embedded objects explicitly defining schema elements _id
option set false:
var userquizschema = mongoose.schema({ uid:{type:objectid,required: true,index:true}, answer:[new schema({content:string, qid:objectid, time:date}, {_id:false})] });
Comments
Post a Comment