Sunday, 30 April 2017

get all users in database and certain fields to array with mongoose

I have a schema which looks like:

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

});

Is there a way which I can get all users in the database, then go the position subdocument, take the pos_index_number and make an object with the preferences sub-subdocument. for example (if there are 4 positions):

array:[
{pos_index_number:candidate_index_number,candidate_index_number,candidate_index_number},
{pos_index_number:candidate_index_number,candidate_index_number,candidate_index_number},
{pos_index_number:candidate_index_number,candidate_index_number,candidate_index_number},
{pos_index_number:candidate_index_number,candidate_index_number,candidate_index_number},
]

and the position in which the 'candidate_index_number' appears in the list is ordered by weightedScore?

I have a query which looks like:

   app.post('/checkPreferences', function(req, res){

        var array =[901,931]; // some pos_index_numbers which returns 2 users

        User.aggregate( { $unwind : "$position" }
        { $match: { "position.pos_index_number": {
          $in: array }
        }}
            , function(err, results){
                  res.send({results:results});
                      console.log(results);

              })
      });

and a sample of the data:enter image description here

So an array would ultimately look like

[
{901:2,3} // because the weightedScore for candidate_index_number 2 is larger than 3
]



via user

No comments:

Post a Comment