Idlliofrio Idlliofrio - 2 months ago 11
Javascript Question

Increment field of another collection in mongodb

I created two collections,one for enterprise and another for employees,their schema is as follows,



var mongoose= require('mongoose');

var Enterprise= new mongoose.Schema({

name:{type:String},
email:{type:String},
sector:{type:String},
employees: {type:Number,default:0}

});


module.exports={
Enterprise:Enterprise
};







var mongoose = require('mongoose');

var employee = new mongoose.Schema({

enterprise:{type: String},
name:{type:String},
email:{type:String},
password:{type:String},
gender:{type:String},
});

module.exports = {

employee:employee
};





my add employee route,



var mongoose = require('mongoose');
var q = require('q');

var employee = mongoose.model('employee');
var enterprise = mongoose.model('enterprise');

var addEmployee = function(req, res) {

newEmployee = new employee();

newEmployee.enterprise = req.params.enterprise;
newEmployee.name = req.params.name;
newEmployee.email = req.params.email;
newEmployee.gender = req.params.gender;

function detailSave() {

var deferred = q.defer();

newEmployee.save(function(err, data) {

if (err) {
res.send(500);
console.log('couldnt save employee details');
deferred.reject({errmessage: 'couldnt save employee details', err: err});
} else {

res.send(200);
deferred.resolve({data: data});
}
});

return deferred.promise;
}

function incrementEmployee(doc) {

var deferred = q.defer();

enterprise.findOneAndUpdate({ 'name': doc.enterprise }, { $inc: { 'employees': 1 } },

function(err, num) {
if (err) {
deferred.reject({errmessage: 'couldnt incrementEmployee', err: err});
res.send(500);
console.log('couldnt incrementEmployee');
} else {
res.send(200);
deferred.resolve({num:num});
}
});

return deferred.promise;

}

detailSave()
.then(incrementEmployee)
.then(function(success) {
console.log('success', success);
res.json(200, success);
})
.fail(function(err) {
res.json(500, err);
})
.done();

};
module.exports = {
addEmployee: addEmployee
};





The problem is when I add an employee, the employees field in enterprise collection doesn't increment

Answer

I think your query is not working since doc.enterprise is null On the basis of your comment.

Try to give your query like this {'name': doc.data.enterprise}

function incrementEmployee(doc) {

  var deferred = q.defer();

  enterprise.findOneAndUpdate({
      'name': doc.data.enterprise
    }, {
      $inc: {
        'employees': 1
      }
    },

    function(err, num) {
      if (err) {
        deferred.reject({
          errmessage: 'couldnt incrementEmployee',
          err: err
        });
        res.send(500);
        console.log('couldnt incrementEmployee');
      } else {
        res.send(200);
        deferred.resolve({
          num: num
        });
      }
    });

  return deferred.promise;

}