Query returning {} when it should return data - node.js

Im having trouble with a mongdb query returning {} from my node.js code.
Here is how I am building my query string in node.js javascript:
var idString = '' + firstId; // firstId = 1
var otheridString = '' + secondId; // secondId = 2
var users = { userid: { $in : [idString, otheridString] }};
But when I run this through nodeJS/mongo it returns {}
If I run this directly in the DB it returns the two rows
db.Users.find({ userid: { $in : ["1", "2"] }})
I think this has something to do with the userid's being strings, as if i run this query directly in the DB it returns {} also
db.Users.find({ userid: { $in : [1, 2] }})
Any help appreciated!

Please try this
var idString = firstId.toString(); // firstId = 1
var otheridString = secondId.toString(); // secondId = 2
var users = { userid: { $in : [idString, otheridString] }};

Related

Mongoose Find() - Return all docs if query is undefined

I have mongoose Find code function , the query is recieved from params (Here currently hardcoded)
Suppose this as the query
var arrayOfCategories = [ '63073212ed3e0f85ccffc8cf' , '63073324ed3e0f85ccffc8ff']
var arrayOfSkill = []
This is my find code
const astro =await Astrologer.find({ 'category.astolCat_id' : {$in: arrayOfCategories},
'skills.astolSkill_id': { $in: arrayOfSkill}})
It works fine if I have a value in 'arrayOfSkill' array but I want it to ignore ''skills.astolSkill_id': { $in: arrayOfSkill}' and only query for arrayOfCategories if arrayOfSkill is blank. If arrayOfSkill is blank then I is returning blank array
Build up your query options progressively...
const query = {};
if (arrayOfCategories.length) {
query["category.astolCat_id"] = { $in: arrayOfCategories };
}
if (arrayOfSkill.length) {
query["skills.astolSkill_id"] = { $in: arrayOfSkill };
}
const astro =await Astrologer.find(query);
const filter = [{}]
arrayOfCategories.length > 0 && filter.push({'category.astolCat_id': {$in: arrayOfCategories}})
arrayOfSkill.length > 0 && filter.push({'skills.astolSkill_id': { $in: arrayOfSkill }})
const astro =await Astrologer.find({$and:filter})
If need, can be modified as ; find({$or: filter})

how to use orderByChild with startAfter in Realtime Database using Node.js

I am trying to sort orders in descending and start after on particular key but its not working
nextAfter : -Mk4-n5BnVpwhum62n2g or any Key / _id
db record:
{
'-Mk4-n5BnVpwhum62n2g': {
_id: '-Mk4-n5BnVpwhum62n2g',
createdAt: -1632171667626,
name: 'abc'
},
'-Mk40Ko9DbSeMdjIpY4': {
_id: '-Mk40Ko9DbSeMdjIpY4',
createdAt: -1632171809831,
name: 'new '
}
}
trying query :
query = dbRef.orderByChild('createdAt').startAfter(nextAfter).limitToFirst(limit);
The startAfter() method accepts two parameters - the first is the relevant orderBy value and the second is the optional key of the last entry (for when multiple entries have the same value for the orderBy criteria). So to correctly paginate the reference, you need to pass the previous entry's createdAt value and its key.
const baseQuery = dbRef
.orderByChild('createdAt')
.limitToFirst(limit);
let pageCount = 0, lastChildOnPage = undefined;
const children = [];
while (true) {
const pageQuery = pageCount === 0
? baseQuery
: baseQuery
.startAfter(lastChildOnPage.createdAt, lastChildOnPage.key);
const pageSnapshot = await pageQuery.once('value');
pageSnapshot.forEach((childSnapshot) => {
children.push({ key: childSnapshot.key, ...childSnapshot.val() });
})
const newLastChildOnPage = children[children.length-1];
if (lastChildOnPage !== newLastChildOnPage) {
lastChildOnPage = newLastChildOnPage;
pageCount++;
} else {
break; // no more data
}
}
console.log(`Grabbed ${pageCount} page(s) of data, retrieving ${children.length} children`);

Shorter way for find() query

I want to find if cell with provided coordinates exists in DB.
Is there a shorter way to create this query?
var schema = new mongoose.Schema({
coors: {
x: String,
y: String
}
});
// coors = {x:'1', y:'2'};
schema.statics.is_cell_exists = function (coors, callback){
var Cell = this;
var coors_x = {};
var coors_y = {};
coors_x['coors'] = {x: coors.x};
coors_y['coors'] = {y: coors.y};
var query = { $and: [coors_x, coors_y] };
Cell.find( query ).exec(...);
};
It just seems you have some unnecessary variables, etc. You can simply use dot notation to get inside that "coors" object and search on it.
Cell.find({ $and : [{ 'coors.x' : coors.x }, { 'coors.y' : coors.y }] })

sequelize dynamic query params

I'm sending query params as JSON format in req.query.p from my front-end MVC framework , the point is that this could be a dynamic key and value, for example:
req.query.p = {nombre : 'juan'}
or
req.query.p = {pais : 'chile'}
So I need the key, and the value to put them in the where statement, something like this
exports.select = function(req, res){
console.log('=> GET | Obtener peliculas'.bold.get);
db.Pelicula
.findAndCountAll({
limit : req.query.limit,
offset : req.query.offset,
where : req.query.p ? [req.query.p.KEY + " = ?", req.query.p.VAL] : null
})
.success(function(resp){
console.log(JSON.stringify(resp.rows, null, 4).bold.get);
res.json({peliculas : resp.rows, meta : { total : resp.count}});
});
}
The where parameter can be an object, so you can just pass where: req.query.p
Usually I put the entire object, so if it comes empty, it will work normally as if there is no conditional WHERE.
You don't need to add {} in the where, because the object that comes from req.query already has it.
const filter = req.query;
example= await ModelExample.findAndCountAll({
where:
filter
})
With ES6 and with usage of the dynamic properties I'll do it like this
const { Op } = require("sequelize");
const from = new Date()
// const to = new Date().setMinutes(40)
const to = null
let where = {
timestamp: {
[Op.or]: {}
}
}
if (from) {
where.timestamp[Op.or][Op.gte] = new Date(from)
}
if (to) {
where.timestamp[Op.or][Op.lte] = new Date(to)
}
console.log(where);
Model.find({ where })

How to pass mongodb match conditions from node.js URL parameters

I have a webpage where users selects variables to filter and get database values. I tried passing the $match condition variables as below but i am not getting any results back
URL is : example.com?gender=M&date_from=20100101&date_to=201140101
I loop through the req.query to build the match condition string.
var matchQuery = [];
for (var param in req.query) {
qString = "{'" + param + "' : '" + req.query[param] + "'}";
matchQuery.push(qString);
}
var strmatchQuery = matchQuery.toString();
This outputs strmatchQuery as {'gender' : 'M'}, {'date_from' : '20100101'}, {'date_to' : '20140101'}
and then I call the mongodb aggregate function
dbmodel.aggregate( { $match: { $and: [ strmatchQuery ]} } , { $group : { _id : "$orderyear", totalorders : { $sum : 1 } } } )
But I dont get any results back. Any ideas?
function is_numeric(num) {
return !isNaN(num);
}
var matchQuery = [];
var qString = {};
for (var param in req.query) {
// You need objects in your query not strings so push objects
qString = {};
qString[param] = is_numeric(req.query[param]) ? Number(req.query[param]) : req.query[param];
matchQuery.push(qString);
}
// Removed the toString() function call
dbmodel.aggregate(
{$match: {$and: strmatchQuery}}, // Removed the array [ ]
{$group: {
_id: "$orderyear",
totalorders: {$sum: 1}}
}
);

Resources