user.save(function (err) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     req.login(user, function (err) {
       if (err) {
         return res.status(400).send(err);
       } else {
         return res.json(user);
       }
     });
   }
 });
    coll.save(function (err) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(coll);

        //create trace log
        traceLogCreate(req, traceConfig.action.AdminCollectionSetRecommendLevel, {
          coll: coll._id,
          recommended: req.params.rlevel
        });
      }
    });
      topic.save(function (err) {
        if (err) {
          return res.status(422).send({
            message: errorHandler.getErrorMessage(err)
          });
        } else {
          res.json(topic);

          r.user.update({
            $inc: {replies: -1}
          }).exec();

          forum.update({
            $inc: {replyCount: -1}
          }).exec();

          Topic.findOne({
            forum: forum._id
          })
            .sort('-lastReplyAt -createdAt')
            .exec(function (err, topic) {
              if (!err) {
                forum.update({
                  lastTopic: topic
                }).exec();
              }
            });

          //add server message
          if (serverNoticeConfig.action.forumReplyDeleted.enable && !replyUid.equals(req.user._id)) {
            serverMessage.addMessage(replyUid, serverNoticeConfig.action.forumReplyDeleted.title, serverNoticeConfig.action.forumReplyDeleted.content, {
              topic_title: topic.title,
              forum_id: topic.forum,
              topic_id: topic._id,
              reply_id: req.params.replyId,
              by_name: req.user.displayName,
              by_id: req.user._id
            });
          }

          //create trace log
          traceLogCreate(req, traceConfig.action.forumDeleteReply, {
            forum: forum._id,
            topic: topic._id,
            reply: req.params.replyId
          });
        }
      });
 Client.find().sort('-created').populate('user', 'displayName').limit(4).exec(function (err, clients) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     Barber.count().exec(function (err, barberCount) {
       if (err) {
         return res.status(400).send({
           message: errorHandler.getErrorMessage(err)
         });
       } else {
         var finishedQuery = { 'status': 1 };
         if (req.query.date) {
           finishedQuery.date = req.query.date;
         }
         Booking.count(finishedQuery).exec(function (err, finishedCustomers) {
           if (err) {
             return res.status(400).send({
               message: errorHandler.getErrorMessage(err)
             });
           } else {
             var waitingQuery = { 'status': 0 };
             if (req.query.date) {
               waitingQuery.date = req.query.date;
             }
             Booking.count(waitingQuery).exec(function (err, waitingCustomers) {
               if (err) {
                 return res.status(400).send({
                   message: errorHandler.getErrorMessage(err)
                 });
               } else {
                 res.json({
                   "barberCount": barberCount,
                   "finishedCustomers": finishedCustomers,
                   "waitingCustomers": waitingCustomers,
                   "barbers": barbers,
                   "clients": clients
                 });
               }
             });
           }
         });
       }
     });
   }
 });
							user.save(function(err) {
								if (err) {
									return res.status(400).send({
										message: errorHandler.getErrorMessage(err)
									});
								} else {
									req.login(user, function(err) {
										if (err) {
											res.status(400).send(err);
										} else {
											res.send({
												message: 'Password changed successfully'
											});
										}
									});
								}
							});
 user.save(function (err) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     req.login(user, function (err) {
       if (err) {
         res.status(400).send(err);
       } else {
         res.send({
           message: 'Senha alterada com sucesso!'
         });
       }
     });
   }
 });
    user.save(function (err) {
      if (err) {
        return res.status(400).send({
          message: errorService.getErrorMessage(err)
        });
      } else {
        req.login(user, function (err) {
          if (err) {
            return res.status(400).send(err);
          }

          // Remove sensitive data before sending out
          user = userProfile.sanitizeProfile(user);
          res.json(user);
        });
      }
    });
exports.handleSave = function(model, models, res, err) {
    if (err) {
        for (var i in models) {
            if (models[i].remove) {
                models[i].remove();
            }
        }

        if (!res.headersSent) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
    } else {
        models.push(models);
    }
};
 user.save(function (err) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     req.login(user, function (err) {
       if (err) {
         res.status(400).send(err);
       } else {
         res.send({
           message: 'Thay đổi mật khẩu thành công'
         });
       }
     });
   }
 });
 unit.validate(function (err) {
   if (err) {
     console.log(err);
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     unit.save(function (err) {
       if (err) {
         return res.status(400).send({
           message: errorHandler.getErrorMessage(err)
         });
       } else {
         res.json(unit);
       }
     });
   }
 });
 user.save(function(err) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     // Remove sensitive data before login
     user.password = undefined;
     user.salt = undefined;
     req.login(user, function(err) {
       if (err) {
         res.status(400).send(err);
       } else {
         res.json(user);
       }
     });
   }
 });
  topic.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(topic);

      forum.update({
        $inc: {topicCount: 1},
        lastTopic: topic
      }).exec();

      user.update({
        $inc: {topics: 1}
      }).exec();
    }
  });
  count(options, req, function (err, counts) {
    if (err) {
      return res.status(400).send({
        messeage: errorHandler.getErrorMessage(err)
      });
    }

    ArticleSender.find(options).sort(sort).populate('user', 'email').limit(limit).skip(skip).exec(function (err, articleSenders) {
      if (err) {
        return res.status(400).send({
          messeage: errorHandler.getErrorMessage(err)
        });
      } else {
        var data = { counts: counts, articleSenders: articleSenders };
        res.json(data);
      }
    });
  });
  Farm.findOne(searchQuery).exec(function(err, farm) {
    if (err) {
      console.log("#### DB error");
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      if (!farm) {
        console.log("#### Not found");
        return res.jsonp(new Farm());
      }
      else {
        console.log("#### Success");
        res.jsonp(farm);
      }

    }
  });
            user.save(function(err) {
              if (err) {
                return res.status(422).send({
                  message: errorHandler.getErrorMessage(err)
                });
              } else {
                user.password = undefined;
                user.salt = undefined;

                var token = authorization.signToken(user);
                res.json({
                  user: user,
                  token: token
                });

                done(err, user);
              }
            });
    function(err, data) {

      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {

        // Sanitize each outgoing thread
        var threadsCleaned = [];
        if(data.docs.length > 0) {
          data.docs.forEach(function(thread) {

            // Threads need just excerpt
            thread = thread.toObject();

            // Clean message content from html + clean all whitespace + shorten
            if(thread.message) {
              thread.message.excerpt = thread.message.content ? textProcessor.plainText(thread.message.content, true).substring(0, 100).trim() + ' …' : '…';
              delete thread.message.content;
            }
            // Ensure this works even if messages couldn't be found for some reason
            else {
              thread.message = {
                excerpt: '…'
              };
            }

            // If latest message in the thread was from current user, show
            // it as read - sender obviously read his/her own message
            if(thread.userFrom._id.toString() === req.user._id.toString()) {
              thread.read = true;
            }

            threadsCleaned.push(thread);
          });
        }

        // Pass pagination data to construct link header
        setLinkHeader(req, res, data.pages);

        res.json(threadsCleaned);
      }
    }
  maker.remove(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(maker);

      //add server message
      if (serverNoticeConfig.action.makerDeleted.enable) {
        serverMessage.addMessage(maker.user._id, serverNoticeConfig.action.makerDeleted.title, serverNoticeConfig.action.makerDeleted.content, {
          maker_name: maker.name,
          site_name: appConfig.name,
          by_name: req.user.displayName,
          by_id: req.user._id
        });
      }
    }
  });
 siteCondition.save(function (err) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     validateSiteCondition(siteCondition, function(siteConditionJSON) {
       res.json({
         siteCondition: siteCondition,
         successful: true
       });
     }, function(errorMessages) {
       res.json({
         siteCondition: siteCondition,
         errors: errorMessages
       });
     });
   }
 });
  DynamicModule.find().sort('-created').populate('user', 'displayName').exec(function (err, dynamicModules) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {


      var dModules = [];
      var itemsProcessed = 0;

      dynamicModules.forEach(function(dModule) {


        DynamicModuleData.count({dynamicModule: dModule._id}).exec(function (err, noOfDynamicModuleDatas) {
          if (err) {
            return res.status(400).send({
              message: errorHandler.getErrorMessage(err)
            });
          } else {

            var ddModule = dModule.toJSON();
            ddModule.noOfDynamicModuleDatas = noOfDynamicModuleDatas;
            dModules.push(ddModule);


            itemsProcessed++;
            if(itemsProcessed === dynamicModules.length) {

              //Sending final O/p
              res.json(dModules);
            }

          }
        });

      });



      //res.json(dynamicModules);
    }
  });
 dispositivo.id_disp_central = Dispositivo.count({ 'central': req.user.central }, function(error, nbDocs) {
   if (error) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(error)
     });
   } else {
     nbDocs += 1;
     dispositivo.id_disp_central = nbDocs;
     dispositivo.save(function (err) {
       if (err) {
         return res.status(400).send({
           message: errorHandler.getErrorMessage(err)
         });
       } else {
         res.json(dispositivo);
       }
     });
   }
 });
    User.findOne({department: dept}).exec(function (err, user) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            complaint.user = user;
            complaint.save(function (err) {
                if (err) {
                    return res.status(400).send({
                        message: errorHandler.getErrorMessage(err)
                    });
                } else {
                    res.jsonp(complaint);
                }
            });
        }

    });
 Invoice.findOne({ token: invoiceToken }).populate('user', 'companyName').populate('client', 'companyName email').exec(function(err, invoice) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     if (invoice) {
       invoice.isRead = 1;
       invoice.save();
       User.findOne({
         accountSetupToken: userToken
       }, function (err, user) {
         if (user)
           require(require('path').resolve('modules/notifications/server/slack/notifications.server.send.slack.js'))(config, invoice, null, user, 0, 11);
       });
       res.jsonp(invoice);
     }
   }
 });
			.exec(function(err, succ) {
				if (err) {
					return res.status(404).json({
						message: errorHandler.getErrorMessage(err)
					});
				} else if (!succ) {
					var body = {
						hackathon: hackathon,
						user: user,
						role: req.body.role
					};
					var member = new HackathonMember(body);
					member.save(function(err, member) {
						if (err) {
							return res.status(404).json({
								message: errorHandler.getErrorMessage(err)
							});
						} else {
							return res.json(member);
						}

					});
				} else {
					if (succ.deleted) {
						succ.role = req.body.role;
						succ.restore(function(err, newMem) {
							if (err) {
								return res.status(404).json({
									message: errorHandler.getErrorMessage(err)
								});
							} else {
								newMem.user = user;
								return res.json(newMem);
							}
						});
					} else {
						return res.status(400).json({
							message: 'User already hackathon'
						});
					}
				}
			});
 query.sort('code').exec(function (err, standards) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     if (req.query.select) {
       var values = [];
       for (var i = 0; i < standards.length; i++) {
         values.push({
           _id: standards[i]._id,
           value: standards[i].code + ' - ' + standards[i].description
         });
       }
       res.json(values);
     } else {
       res.json(standards);
     }
   }
 });
 message.save(function (err) {
   if (err) {
     return res.status(422).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     Message.populate(message._replies, {
       path: 'from_user to_user',
       select: 'displayName profileImageURL uploaded downloaded'
     }, function (err, t) {
       if (err) {
         return res.status(422).send({
           message: errorHandler.getErrorMessage(err)
         });
       } else {
         res.json(message);
       }
     });
   }
 });
 ArticleSender.findById(id).populate('user', 'displayName').exec(function (err, articleSender) {
   if (!err) {
     if (articleSender._id !== undefined && articleSender.status === 'Sent') {
       console.log(articleSender._id);
       articleSender.status = 'ReSend';
       articleSender.emails = emails;
       articleSender.save(function (err) {
         if (err) {
           return res.status(400).send({
             messeage: errorHandler.getErrorMessage(err)
           });
         }
       });
     }
   } else {
     return res.status(400).send({
       messeage: errorHandler.getErrorMessage(err)
     });
   }
 });
	}).exec(function(err, item) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else if (!item) {
			return res.status(400).send({
				message: 'User not found'
			});
		} else {
			item.softdelete(function(err) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					res.json(req.hackathon);
				}
			});
		}
	});
 Portfolio.find().sort('-created').populate('user', 'displayName').exec(function (err, items) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     var response = {};
     // response.items = items;
     response.websites = [];
     response.projects = [];
     for(var i in items) {
       var item = items[i];
       if(item.type === 'website') {
         response.websites.push(item);
       } else if(item.type === 'project'){
         response.projects.push(item);
       }
     }
     res.json(response);
   }
 });
 MetaNgssScienceEngineeringPractice.find().sort({ 'header': 1, 'description': 1 }).exec(function (err, standards) {
   if (err) {
     return res.status(400).send({
       message: errorHandler.getErrorMessage(err)
     });
   } else {
     if (req.query.select) {
       var values = [];
       for (var i = 0; i < standards.length; i++) {
         values.push({
           _id: standards[i]._id,
           header: standards[i].header,
           value: standards[i].header + ' - ' + standards[i].description
         });
       }
       res.json(values);
     } else {
       res.json(standards);
     }
   }
 });
        user.save().then(function(saved) {
          if (!saved) {
            return res.status(400).send({
              message: errorHandler.getErrorMessage(saved)
            });
          } else {
            if (oldImage) {
              try {
                var stats = fs.lstatSync('./public/uploads/users/profile/' + oldImage);
                if (stats.isFile()) {
                  fs.unlinkSync('./public/uploads/users/profile/' + oldImage);
                }
              } catch (e) {
                console.log('Unable to delete the old image', e);
              }
            }

            req.user.profileImageURL = user.profileImageURL;
            res.json(user);
          }
        }).catch(function(err) {