Monday 1 May 2017

check if number exists in subdocument with Mongoose

I have a document which looks like:

var User = new Schema({
    _id: ObjectId,
    name: String,
    position: [{
              _id:ObjectId,
              index_number:Number,
                    preference:[{
                        candidate_id: String,
                        weightedScore:Number,
                        position_id:String,
                        candidate_index_number:Number
                    }],

When I add a position, I generate an index_number using var index_number = Math.floor(100000 + Math.random() * 900000);

But I need to check if this number exists in the subdocument for any other position before I add it. So i need to check the number, and run the function again if number does exist, until i get a number that doesn't.. But this function doesn't go into the sub document..

 User.count({index_number: index_number}, function (err, count){
      if(count>0){
            console.log("no");
      }
      else{
          console.log("okay");
      }

how do I loop through the function and check the sub documents for the index_number? or is there a way that I am unaware of that allows me to insert a unique number that isn't an object Id with Mongoose?



via user

No comments:

Post a Comment