Tuesday 16 May 2017

Mongoose get id from related model before save

I have to two models:

work order

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const workOrderSchema = Schema({
    code: {
        type: String,
        required: [true,'Code no puede estar vacio']
    },
    description: {
        type: String
    },
    workOrderTypeId: {
        type: Schema.Types.ObjectId,
        ref: 'work_order_types',
        required: [true,'workOrderTypeId no puede estar vacio']
    },
    requestedOn: {
        type: Date,
        required: [true,'requestedOn no puede estar vacio']
    },
    batches: {
        type: Schema.Types.ObjectId,
        ref: 'batches',
    }
}, {timestamps: true});

const workOrder = module.exports = mongoose.model('work_orders', workOrderSchema);

Batch:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const counter = require('./../parameters/counter');

const batchSchema = Schema({
    batchNumber: {
        type: String,
        //required: [true,'batchNumber no puede estar vacio']
    },
    startedOn: {
        type: Date,
        required: [true,'startedOn no puede estar vacio']
    },
    completedOn: {
        type: Date
    },
    status: {
        type: Boolean,
        default: false
    }
}, {timestamps: true});

batchSchema.pre('save', function(next) {
    var doc = this;
    counter.findByIdAndUpdate({
        _id: 'batchNumber'
    }, {
        $inc: {
            seq: 1
        }
    }, function(error, counter) {
        if (error)
            return next(error);
        doc.batchNumber = counter.seq;
        next();
    });
});

const Batch = module.exports = mongoose.model('batches', batchSchema);

A bacth can only have 24 work orders.

I was trying to count the batches in the model work order like this:

utilitiesFunctions.conteoBatch = (options, callback) => {

  workOrder.aggregate({
    $unwind: "$batches"
  }, {
    $group: {
      _id: "$batches",
      total: {
        $sum: 1
      }
    }
  }, function(err, conteos) {
    if (err) {
      callback(err, conteos);
    }
    callback(err, conteos);
  });
}

In the work order controller I get the array of results:

workOrderController.insert = (options, callback) => {
  utilitiesFunctions.conteoBatch({}, (err, conteos) => {
    if (!err) {
      console.log({'Conteo Batches ':conteos});
    }
  });
   workOrder.create(workorder, callback);
}

the result:

{ 'Conteo Batches ': 
   [ { _id: 591bbceec7c7a70d3626ae5f, total: 24 },
     { _id: 58f3e7eedf0dd8250179b790, total: 7 } ] }

How can I extract the batch id and the count and pass it before save the work order document.

If all the batches already have 24 woirk orders create a new batch and get the id to save in the work order document

Thanks in advance



via joselegit

No comments:

Post a Comment