user824624
user824624

Reputation: 8080

adding multiple same documents using addtoset command in mongoose

My schema is

var UserQuizSchema = mongoose.Schema({   
        uid:{type:ObjectId,required: true,index:true},
        answer:[{content:String, qid:ObjectId ,time:Date }],        
});

In this schema, 'uid' represents user identifier, while the 'answer' array stores the answers the student had answered. in each answer, qid relates to the question ID, and 'content' is the student's real answer, 'time' is the modified time stamp for the answer.

Here I use mongoose to upsert the new answers into the 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 the common sense, by using addToSet command, the element in the answer array should be unique, but in my example, the answer array could have multiple same embedded documents only except each embedded document has one unique OjbectId _id

such as

 answer:
  [ { qid: 5175aecf0e5b061414000001, _id: 518a5e5895fc9ddc1e000003 },
    { qid: 5175aecf0e5b061414000001, _id: 518a5e5f95fc9ddc1e000004 } ] }

you see the qid of two embedded documents are the same, but _id are different.

Why there is a additional _id, I don't put it the schema design ??

Upvotes: 3

Views: 1838

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

You can disable the _id in your embedded objects by explicitly defining a schema for the elements with the _id option set to false:

var UserQuizSchema = mongoose.Schema({   
    uid:{type:ObjectId,required: true,index:true},
    answer:[new Schema({content:String, qid:ObjectId, time:Date}, {_id:false})]
});

Upvotes: 6

Related Questions