Firebase where query - node.js

I have a problem, here is the code:
const firstName = "rick";
const users = await db.collection('user');
if (firstName != undefined) {
users.where("name", "==", firstName );
}
const snap = users.get();
why this query return me the whole document with all objects? How to do a query based on where clause that can be null or undefined? Thanks for any help!

You are not reassigning the users and hence it's fetching whole collection. Try refactoring like this:
let users: firebase.firestore.Query = db.collection('user');
//^ let instead of const
if (firstName) {
users = users.where("name", "==", firstName );
// ^^ updating original 'users' value
}
const snap = users.get();

Related

object is not update within map function and await too

Actually am getting details from cart table it display an array of objects , that object contains product id and quantity , after that i want to include price and name for my local display so i want to update the object for my reference, but name and price contains another table . here my code
exports.cartList = async (req, res) => {
const CartId = req.profile.CartId;
await Cart.findById(CartId).then(data =>
{
const products = data.products;
const exprd = products;
const length = products.length;
exprd.map((item, index) =>
{
const prodID = item.productId;
const quantity = item.quantity;
Product.findById(prodID).then(prdDet => {
const price = prdDet.price;
const inven = prdDet.inventory;
const name = prdDet.name;
console.log(name);
console.log('CHECKERSP');
if(quantity < inven)
{
({ ...exprd, stock: 'stock', })
}
else
{
({ ...exprd, stock: 'Out of Stock', })
}
({ ...exprd, name: name, price: price })
});
console.log('ex2',exprd);
})
console.log('ex1',exprd);
res.json(exprd)
});
}```
but object is not updated , i don't know what i did wrong because am very new to these things . Help me to overcome this problem, Thanks in advance.
First I think you have missed await before "Product.findById(prodID)"
Further,
In if and else block you have to assign the value after declaration.
Example:
let obj ={name:'XYZ'};
Either it should be:
let obj1 = {...obj, name:'ABC'};
Or
obj = {...obj, name:'ABC'};
Furthermore, If you are doing await inside a loop,
traditional loops are better. Map, filter and all can be tricky and await might not act as desired.
Kindly let me know if there is anything missing or wrong...
Just working things according to the funny experiences I acquired.
Hope this helps.

Mongoose Model.find() methods query string not working

im trying to make simple rest api. I have a collection in mongodb and i connected my db to my app with mongoose pkg. I can access all items without query strings with Operator.find() but it doesn't work with query string ex: Operator.find({name:'Kapkan'}) it returns all of them. Also Operator.findOne({name:'Azami'}) doesn't work either. The query string returns the first element of the collection no matter what.
app.get('/api/operators',async(req,res) => {
let operators;
try{
if(req.query.name){
Operator.find({name:'Kapkan'}).then((data) => {
console.log(data);
});
}
else
operators = await Operator.find();
res.send(operators)
}catch(er){
console.log(er);
}
})
You are not assigning result of query with filter to operators. Unsure if you have {} around else or not but try refactoring the code as shown below:
app.get('/api/operators',async(req,res) => {
const filters = {};
if (req.query.name) {
filters.name = req.query.name;
}
const data = await Operator.find(filters);
console.log(data);
return res.json({ data });
})
I checked my Schema and i realize i forgotten put name field...
const OperatorSchema = new Schema({
_id:Number,
logo:String,
image:String,
unit:String,
*name:String,
side:String,
.
.
.
})

MongoDb query by _id using Node

const cCurser = await client
.db("Database")
.collection("Collection")
.findOne({
_id: ObjectId(Filter)
}).then(function(item){
Obj = item;}
);
I'm trying to query the MongoDB by the _id but it returns Promise { }. please help me to retrieve the data in it.
Error detected:ReferenceError: ObjectId is not defined
add this before your query:
import mongoose from 'mongoose';
const { ObjectId } = mongoose.Types;
OR:
use this:
const cCurser = await client
.db("Database")
.collection("Collection")
.findOne({
_id: new mongoose.Types.ObjectId(Filter)
}).then(function(item){
Obj = item;}
);
Firstly, don't mix await syntax with the then syntax.
Either use await
let Obj = null;
const cCurser = await client
.db("Database")
.collection("Collection")
.findOne({
_id: ObjectId(Filter)
});
//Use Obj
Or the then syntax. Here you will have to write the rest of the code dependent on Obj inside then().
let Obj = null;
const cCurser = client
.db("Database")
.collection("Collection")
.findOne({
_id: ObjectId(Filter)
}).then(function(item){
Obj = item;
//Use Obj
}
);
Also based on your edit,it seems you have not imported ObjectId method from Mongo.
let mongo = require('mongodb');
let ObjectId = mongo .ObjectID
```

how do I add multiple filtering to product in mongoose

how do I add filtering to product in mongoose and the filtering will have some foreign reference such
as category, brand ,color?
after receiving the category and brand as slug , i query them on their model to find the _id
my code:
let category = req.query.category || ''
let brand = req.query.brand || ''
if(!category && !brand){
allProduct = await Product.find({admin_id:admin_id , is_active:true})
.sort({ _id: -1 })
.select(select)
.skip((page-1) *limit)
.limit(limit)
}
else if(category&& !brand && !...){
allProduct = await Product.find({admin_id:admin_id , is_active:true ,
category_ids:category._id})
.sort({ _id: -1 })
.select(select)
.skip((page-1) *limit)
.limit(limit)
}
Here the query parameter has the slug as value not _id, I have to find the product that matches
foreign _id. I did query to find the _id of brand category by using slug value.
This query parameter can sometimes be null and sometimes has both value exits.
I am using mongoose. How to complete this query because now it looks not ok. cause i may have to
filter
CATEGORY BRAND COLOR AND SO ON
So how to complete this query .
similarly it looks rough and for many query option i have to go and check lots of condition.
And i am very limited with my knowledge.
So the solution i came up with is to create an object with all the query fields.
initially i will have an empty object. then if the Query Params is active i search for it's it, and push the _id to my object.The Query Params will have slug as input.
such as:
const query ={}
let category = req.query.category
const cat_id = await Categoryl.find({slug:category }).select('_id')
cat_id? query.category_id = cat_id._id ? null
cont product = await Product.find(query)
make sure all the instance or key's of query object must be same as the Product Schema
such that :
if Product model has category_id then put same key in query
query.category_id =n....
Below i have attached my solved code.
exports.getProduct = async (req, res, next)=>{
try {
const admin_id = req.params.admin_id
const limit = +req.query.limit || 10
const page = +req.query .page || 1
const search = req.query.search || ''
let category = req.query.category
let brand = req.query.brand
const query ={}
query.admin_id =admin_id,
query.is_active = true
if(category){
category = await Category.findOne({admin_id:admin_id , is_active:true, slug:category}).select('_id')
category ?query.category_ids = category._id :null
}
if(brand){
brand = await Brand.findOne({admin_id:admin_id , is_active:true,slug:brand}).select('_id')
brand ? query.brand_id = brand._id.toString() : null
}
let allProduct = []
const count = await Product.find({admin_id:admin_id ,
is_active:true}).countDocuments()
const select = 'name slug photo price special_price new_to special_price_end
newProduct -_id'
allProduct = await Product.find({...query})
.sort({ _id: -1 })
.select(select)
.skip((page-1) *limit)
.limit(limit)
return res.status(200).json({
count:count,
body:allProduct,
error:false
})
} catch (error) {
return res.status(400).json({
error:true
})
}
}

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

Resources