Mongoose: how to call my functions - mongodb

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);
});

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);
}
});
});

How to properly add two conditions to mongodb find()?

Having trouble with finding data. I have to conditions:
1. Matching ID
2. Time range
It works fine when use find() only by id, but there is a polling error when I try to use both or only time.Here what I have so far:
findRange: function (dateRange, callback) {
ExpenseModel.find(
{telegramId: dateRange.telegramId,
time:{
$gt: ISODate(dateRange.from),
$lte: ISODate(dateRange.to)
}},
function (err, existingSequence) {
if (err) {
callback(err, null);
return;
}
if (existingSequence) {
callback(null, existingSequence);
} else {
console.log("not found")
callback(null, false);
}
}
);
}
You have to use $and property
findRange: function (dateRange, callback) {
ExpenseModel.find({$and : [
{ telegramId: dateRange.telegramId},
{ time:{
$gt: ISODate(dateRange.from),
$lte: ISODate(dateRange.to)
}
}
]
},
function (err, existingSequence) {
if (err) {
callback(err, null);
return;
}
if (existingSequence) {
callback(null, existingSequence);
} else {
console.log("not found")
callback(null, false);
}
}
);
}

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) {
// ...
});

MEAN: Getting total value from 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);
});
}

Sails query model always returns undefined

I want to get all stream data with thread value but not including null. On my mongodb console it works with $ne but on my query sails model it always returns undefined?
Example query:
Stream.findOne({thread: {$ne: null } }, function(err, st){
if(err) return err;
console.log("st", st);
});
How can I resolve this?
Use the .native() method:
Stream.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({
"thread": { "$ne": null }
}).toArray(function(err, st) {
if (err) return res.serverError(err);
console.log("st", st);
return res.ok(st);
});
});
Or the .where() method:
var myQuery = Stream.find();
myQuery.where({'thread':{ '$ne': null}});
myQuery.exec(function callBack(err, results){
console.log(results)
});