Sails query model always returns undefined - mongodb

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

Related

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?

Mongoose find between dates, order by ID

So I am trying to find all documents in a database between 'X' and 'X' dates and then order those by userID. This is what I have so far:
await Expense.find(
{'date' :{'$gte': new Date(startDate), '$lte': new Date(endDate)}}),{sort: {_id: 1}}.exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray);
But it keeps giving me "TypeError: {(intermediate value)}.exec is not a function"
For added clarification I am trying to write this in mongoose:
"SELECT employeeName, SUM(amount)
FROM reimbursements
WHERE d8 BETWEEN '$startDate' AND '$endDate'
GROUP BY employeeName
ORDER BY employeeName;";
What am I doing wrong? Thank you in advance :D
Your query has few syntax issues, Please try this :
Update :
Below old code will work, but it would be better if you try this way :
try {
let data = await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 })
/** .find() will not return null, it will either return [] or [with matched docs] */
if (data.length) { // checks data != []
console.log(data)
} else { // data == []
console.log('Empty - no docs found')
}
} catch (error) {
console.log('Error Fetching Model');
console.log(error);
}
Old :
await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 }).exec(function (err, data) {
/** sort is not an option for .find() not like aggregate, it has to be on cursor which is result of .find() & .exec() should be at end which is either .find() or .sort() */
if (err) {
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray)
})
Sample : mongooseModel.find().sort().exec()
Ref : cursor.sort

Nested query in Mongo not working in Meteor

I have some trouble making queries inside a callback running in Meteor Mongo. Anyone is seeing what I am doing wrong here? Thanks!
var houseInserted = Houses.insert({
building_number: address.building_number,
},function(error, results){
if(error) throw error;
console.log(results); // runs
Meteor.users.update( { _id: this.userId }, // Does not execute
{ $set: { 'profile.housed': true , 'profile.address' : results }
}, function(err, doc){
if (err) throw err;
console.log(results); // runs
console.log(doc);
});
console.log(results); // runs
}
);

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

findAndModify with remove true not removing whole document

Using monk:
var doc =
yield new Promise(function (resolve, reject) {
tokens.findAndModify({
query: {
token: myTokenVar
},
remove: true,
new: false
}, function (err, res) {
if (err)
throw err;
resolve(res);
});
});
The following code above removes every field from the given document but however leaves the document with only the _id field left. It does not completely remove the document.
According the findAndModify source code, the opts object must be provided as a separate parameter. Please try it with the following codes
tokens.findAndModify(
{ query: {
token: myTokenVar
}},
{remove: true, 'new': false},
function (err, res) {
if (err)
console.log(err);
else
console.log(res);
});