MEAN: Getting total value from mongodb - mongodb

Im new to mean stack and Im using mongoskin to connect to mongodb..Im trying to get total value present in database
function getTotal() {
var deferred = Q.defer();
var dashboard = db.collection('dashboard');
db.collection('dashboard').find({"iscorrect" : ""}).count(),
function (err, doc) {
if (err){
deferred.reject(err);
} else{
deferred.resolve();
}
};
return deferred.promise;
}
my main controller has
function gettotal(req, res) {
userService.getTotal()
.then(function () {
res.sendStatus(200);
})
.catch(function (err) {
res.status(400).send(err);
});
}
The following code does not return any value...Any help in getting total value is helpful

Because count() method is asynchronous and returns a promise, you can restructure your function as either using a callback function
function getTotal() {
var deferred = Q.defer();
db.collection('dashboard').count({"iscorrect" : ""}, function (err, result) {
if (err){
deferred.reject(err);
} else{
deferred.resolve(result);
}
});
return deferred.promise;
}
or since count() returns a Promise, just return it
function getTotal() {
// just return a Promise
return db.collection('dashboard').count({"iscorrect" : ""});
}
and in your controller:
function gettotal(req, res) {
userService.getTotal()
.then(function (count) {
res.status(200).json({ 'count': count });
})
.catch(function (err) {
res.status(400).send(err);
});
}

Related

How to add attribute to the result of mongoose query before res.status(200).send(result);

I am trying to build a CRUD API that query a mongodb. I want to add another attribute (temperature) to the query result before sending it back to the client. Particularly, I would like to do something where the arrow pointed in the code below.
app.get('/items/:name', function (req, res) {
console.log("get items by name");
Item.find({ name: req.params.name }, function (err, result) {
if (err) {
res.status(400).send(err.message);
} else {
res.status(200).send(result); // <<<<====== Here
}
});
});
How can I achieve this function? Thank you.
i think this below way to help you:
app.get('/items/:name', function (req, res) {
console.log("get items by name");
Item.find({ name: req.params.name }, function (err, result) {
result = {
temperature: yourTemperatureValue,
...result
} // <<<<====== Here
if (err) {
res.status(400).send(err.message);
} else {
res.status(200).send(result);
}
});
});

Mongoose Library find / findOne Method is not returning value when the search dont match with the document

I am facing one issue with Mongoose. When I use find or findOne method and there is no matching results, then callback function is not returning null / err and hung the process. Using Mongoss 5.1.5 , MongoDB V3.4.2. Please advise
module.exports.validateappsubscripition = function (userid, appkey, cb) {
//console.error(userid + ' ' + appkey)
var userobj_id = mongoose.Types.ObjectId(userid);
appsubscripitions.model.findOne({'subscribersuserid': userobj_id , 'appkey'
:appkey }, function(err,doc){
console.error('test2');
if(doc ){
cb(null, doc );
}
else{
cb(null, null );
}
} );
}
Calling Block : Trying to validate the key from req header. I am trying to call the function validateappsubscripition from below block.
module.exports.sendEmail = function (req, res, next) {
let appkey;
let userid;
if (req.headers.appkey) {
appkey = req.headers.appkey;
console.error(appkey);
}
else {
appkey = '';
}
if(req.user._id){
userid = req.user._id ;
console.error(userid);
}
if (!req.body.fromEmail || !req.body.toEmail || !req.body.subject || !req.body.content) {
res.json({ success: false, msg: 'Please pass all the required parameters' });
next();
}
appsubcripitions.validateappsubscripition(userid, appkey, function (err, doc) {
console.error('test2');
if (err) {
res.json({ success: false, msg: 'Unauthorized. App Key is misssing on the header or App key is not valid' });
next();
}
else if (doc ) {
this.getSMTP('smtp.gmail.com', 'arbalu#gmail.com', function (err, userInfo) {
if (err) {
res.json({ success: false, msg: err.message });
next();
}
if (userInfo) {
//userInfo = user;
var send = require('gmail-send')({
user: userInfo.user,
pass: userInfo.pass,
from: req.body.fromEmail,
to: req.body.toEmail,
subject: req.body.subject, // Override value set as default
text: req.body.content
});
send({ // Overriding default parameters
// to: req.toEmail,
// subject: req.subject, // Override value set as default
// text: req.content
// files: [filepath],
}, function (err, response) {
//console.log('* [example 1.1] send() callback returned: err:', err, '; res:', res);
if (err) {
res.json({ success: false, msg: err.message });
next();
}
else {
res.json({ success: true, msg: response });
next();
}
});
}
})
}
else {
res.json({ success: false, msg: 'Some issue on sending email.Please contact the support.' });
next();
}
});
}

Bulk deleting documents from aggregate

I am trying to use a bulk delete on the results of a mongoose aggregate query.
var bulk = Collection.collection.initializeUnorderedBulkOp();
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec();
cursor.each(function(error, doc){
if(doc){
console.log(doc);
bulk.find({_id : doc._id}).removeOne();
}
});
if(bulk.length > 0) {
bulk.execute(function(error){
if(error){
console.error(error);
callback(error);
}else{
console.log(bulk.length + " documents deleted");
callback(null);
}
});
} else {
console.log("no documents to delete");
callback(null);
}
This results in the "no documents to delete" being printed before the results of the aggregate in the each loop. Normally I would expect there to be a callback function for a database operation. I have tried adding a callback function to the params of exec, but the function never gets hit:
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec(function(error, result){
console.log(error);
console.log(result);
callback();
});
Listen to the data and end events on the cursor:
cursor.on( 'data', function( data ) {
bulk.find( { "_id" : data._id } ).removeOne();
});
cursor.on( 'end', function() {
if ( bulk.length === 0 ) {
callback();
} else {
bulk.execute(function (error) {
if (error) {
callback(error);
} else {
callback();
}
});
}
});
What version of Mongoose? There's an issue on github that might be relevant. So maybe try:
var stream = Model
.aggregate(pipeline)
.cursor({ batchSize: 1000 })
.exec().stream();
stream.on('data', function(doc) {
// ...
});

Mongoose update array of Object id's using Populate?

I am trying to populate my array of an object id's how can i do ??
Function
$scope.assignEmployees = function () {
var chkArray = [];
var companyName = $scope.selectedComapny.companyName;
var Indata = {chkvalue:chkArray,company_name:companyName};
$("#employee_name:checked").each(function() {
chkArray.push($(this).val());
});
$http({
method : 'PUT',
url : '/api/projects',
data : Indata
})
.success(function (data){
console.log(data);
});}
Mongoose api
Population code:-
Project.findOne({client : company_name})
.populate('assignedTo')
.exec(function(err, project) {
if (err) return;
while(i<employee_id.length){
project.assignedTo.push(employee_id[i]);
project.save(function(err) {
if (err) return;
})
i++;
}
});
This code is work but it insert value 4 times any idea guys.
You can use this code to push all elements of Array to an Array in mongoose.
Project.update(
{ client: company_name },
{ "$pushAll": { "assignedTo": employee_id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);

Mongoose: how to call my functions

I'm unable to call the calc function. Why?
MyModel.find(
{
$where: function() {
return calc(this) > 500;
}
},
function (err, results) {
if (err) return console.error(err);
console.log(results);
});
function calc(obj) {
return obj.x + obj.y;
}
The code of the $where is sent to the server for execution, so it can only reference functions within its own scope (as well as the built-in function listed here).
So your code would have to be restructured with calc defined in scope:
MyModel.find(
{
$where: function() {
function calc(obj) {
return obj.x + obj.y;
}
return calc(this) > 500;
}
},
function (err, results) {
if (err) return console.error(err);
console.log(results);
});