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

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

Related

Update field using previous value (mongodb) [duplicate]

Is it possible, using mongoose middleware, to increment two fields one with a condition and the other without? In this case i want to increment "stats.ratings" by one, if the user inserts an input greater than 0, else increment zero.
"stats.answered" always increments one
See code below
module.exports.updateStats = function (req, res) {
var rating = parseInt(req.body.rating, 10);
var wasRated;
if (rating > 0) {
wasRated = true;
} else wasRated = false
Collection.findOneAndUpdate({
_id: req.body._id
}, {
$cond: {
if: wasRated,
then: {
$inc: {
"stats.answered": 1,
"stats.ratings": 1
}
},
else: {
$inc: {
"stats.answered": 1,
"stats.ratings": 0
}
}
}
},
function (err, doc) {
if (err)
throw err;
res.status(200);
})
}
What you can do is this:
// define the default case
var update = {
$inc: {
"stats.answered": 1
}
};
if(parseInt(req.body.rating, 10) > 0) {
// override default in some cases
update = {
$inc: {
"stats.answered": 1,
"stats.ratings": 1
}
}
}
and then
Collection.findOneAndUpdate({
_id: req.body._id
}, update,
function (err, doc) {
if (err)
throw err;
res.status(200);
})
}

MongoDB find between the dates

I've got the next data in the MongoDB:
{
...
name: Alex,
createdAt: {"$date":"2021-03-09T20:01:57.488Z"},
...
}
And I try to implement the range date query like this:
MongoClient.connect(url, (err, db) => {
if (err) {
return reject(err);
}
const dbo = db.db('dbname');
dbo.collection('users').find({
createdAt: {
$gte: new Date(dateFrom).toISOString(),
$lt: new Date(dateTo).toISOString()
}
}).toArray(
(err, res) => {
if (err) { return reject(err); }
db.close();
return resolve(res);
});
});
And always have zero-result without errors..
How coud I do the right query?

how to solve TypeError: collection.update(...) is not a function in mongodb?

I am getting this error only on update().
collection.update({ Id: parseInt(orderId) }, { $set: { status: updatedStatus } })
(function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
console.log('updated successfully');
}
and my mongoldb version is "mongodb": "^3.0.2".

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