I can't do a search with the _id query on Mongodb - database

I have a 'items' collection and I can't do a search with the _id query on it.
await client.connect();
const categoriesCollection = client.db('groseriarShop').collection('categories');
const itemsCollection = client.db('groseriarShop').collection('items');
console.log('Database connected')
// items API
app.get('/items', async (req, res) => {
const query = {};
const cursor = itemsCollection.find(query);
const items = await cursor.toArray();
res.send(items)
});
app.get('/items/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
***const item = await itemsCollection.findOne(query);***
console.log(item)
res.send(item);
})
My item is null. but why?

Related

Object (promise.all) to useState

I am trying to set an object to useSate.
The object is the dataMap which should be passed to the setResults
Any help would be appreciated ?
export default function Home() {
const [results, setResults] = useState([]);
const fetchResults = async () => {
const res = await fetch(
'someurl'
);
const data = await res.json();
const dataMap = data.reduce((acc, curr) => {
return {
...acc,
[curr.id]: curr
};
}, {});
const requests = Object.keys(dataMap).map(async (productId) => {
const request = await fetch(
`someUrl/${productId}`
);
const response = await request.json();
return response;
});
const responseAll = await Promise.all(requests);
responseAll.forEach(
({ id, color }) => (dataMap[id] = { ...dataMap[id], color })
);
//console.log(dataMap);
setResults(dataMap)
};
const requests = Object.keys(dataMap).map(async (productId) => {
const request = await fetch(
`someUrl/${productId}`
);
const response = await request.json();
return response;
});
This piece of code will trigger all the api's till the end of Object.keys(dataMap)
To update the state with the values.
You need to update the state just after await like this:
const requests = Object.keys(dataMap).map(async (productId) => {
const request = await fetch(
`someUrl/${productId}`
);
const response = await request.json();
setResults(prev=>[...prev,response])
});

Finding effective way to fetch data from mongo db

I want to fetch data from mongodb by using document property similarly like findById() method I can fetch with query but I want to display data on another page
This is my api code for fetching data
const User = require("../models/User");
const Image = require("../models/Image");
const addImage = async (req, res, next) => {
const newImage = new Image({ userId: req.user.id, ...req.body });
try {
const saveImage = await newImage.save();
res.status(200).json("Image uploaded");
} catch (error) {
next(error);
}
};
// GETPRODUCTBYID :-
const getImage = async (req, res) => {
try {
const image = await Image.findById(req.params.id);
res.status(200).json(image);
} catch (error) {
res.status(500).json(error);
}
};
// GET ALL PRODUCTS :-
const getAllImages = async (req, res) => {
const qNew = req.query.new;
const qCategory = req.query.category;
const qBrand = req.query.brand;
try {
let images;
if (qNew) {
images = await Image.find().sort({ createdAt: -1 }).limit(1);
} else if (qCategory) {
images = await Image.find({
categories: { $in: [qCategory] },
});
}
if (qBrand) {
images = await Image.find({ brand: "Honda" });
} else {
images = await Image.find();
}
res.status(200).json(images);
} catch (error) {
res.status(500).json(error);
}
};
// GET IMAGES BY BRAND :-
const getImagesByBrand = async (req, res) => {
const qBrand = req.query.brand;
try {
const images = await Image.find( {brand: qBrand});
res.status(200).json(images);
} catch (error) {
res.status(500).json(error);
}
};
module.exports = Object.freeze({
addImage,
getImage,
getImagesByBrand,
getAllImages,
});
Structure of document in mongo db
Document
_id
brand
I want to fetch data with brand property and show it on new page it is possible?

discord.js sharding issue in fetching guild

how do i check in discord.js sharding speciic guild id include in my client or not?
const getServer = async (guildID) => {
// try to get guild from all the shards
const req = await client.shard.broadcastEval((c, id) => c.guilds.cache.get(id), {
context: guildID
});
// return Guild or null if not found
return req.find(res => !!res) || false;
}
app.get('/test', checkAuth, async (req, res) => {
let Data =[];
req.user.guilds.forEach(async guild => {
const permsOnGuild = new Permissions(guild.permissions_new);
if(!permsOnGuild.has(Permissions.FLAGS.MANAGE_GUILD))return
if(await getServer(guild.id)){
Data.push(guild)
}
})
return res.render('test.ejs', { perms: Permissions,data:Data,client:client, user: req.user});
});

Deletion in FireStore (Latest Snip)

I have a Data Table i want to delete every document inside collection before invoke loadCheckOut.
How can i dow that with latest JS Syntax.
I am using React JS, and it initilize DB from getDb() method so methods like db.collection() not work on it i want a complete moduler solution
const loadCheckout = async (priceId) => {
//before adding we must delete existing collection
const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
const docRef = await addDoc(
collection(db, `customers/${user.uid}/checkout_sessions`),
{
price: priceId,
success_url: window.location.origin,
cancel_url: window.location.origin,
}
);
const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
const snap = onSnapshot(
ref,
{ includeMetadataChanges: true },
async (doc) => {
var error = null,
sessionId = null;
var first = true;
doc.forEach((ele) => {
if (first) {
error = ele.data().error;
sessionId = ele.data().sessionId;
first = false;
}
});
console.log(sessionId);
if (error) {
alert(error);
}
if (sessionId) {
const stripe = await loadStripe(stripe_public_key);
stripe.redirectToCheckout({ sessionId });
}
}
);
};
This won't work:
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
The deleteDoc function requires a single DocumentReference, while your snapshot is a QuerySnapshot. This has very little to do with the change in syntax, as snapshot.delete() also wouldn't have worked in v8 of the SDK and earlier.
To delete the documents in the query snapshot, loop over the results and delete them one by one:
snapshot.forEach((doc) => {
deleteDoc(doc.ref);
});

React Native wait for async func

I wanna add multiple photo to db by Array.map() and after that add Array with url storage to collection.
I have problem with async function, because i should wait for this function await addImages() but something is not good.
const addImages = async () => {
image.map(async (imagePhoto) => {
const childPath = `post/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`;
const response = await fetch(imagePhoto);
const blob = await response.blob();
const task = firebase
.storage()
.ref()
.child(childPath)
.put(blob);
const taskProgress = snapshot => {
console.log(`transferred: ${snapshot.bytesTransferred}`)
}
const taskCompleted = () => {
task.snapshot.ref.getDownloadURL().then((snapshot) => {
imageDB.push(snapshot)
})
}
const taskError = snapshot => {
console.log(snapshot)
}
task.on("state_changed", taskProgress, taskError, taskCompleted);
})
}
const addToDbServices = async () => {
await addImages();
firebase.firestore().collection("services")
.doc(firebase.auth().currentUser.uid)
.collection("userServices")
.add({
nameService,
errorCode,
description,
imageDB,
status,
creation: firebase.firestore.FieldValue.serverTimestamp()
}).then(() => {
Alert.alert('Serwis', 'Twoje zgłoszenie zostało pomyślnie dodane'),
navigation.goBack()
})
}
image.map(async (imagePhoto) => {...})
This creates an array of promises. These are executed but not awaited by default, so code execution continues regardless whether the operations are finished or not. If you want to await all these promises you can use Promis.all() like that:
const addImages = async () => {
const pendingOperations = image.map(async (imagePhoto) => {...});
// wait until all images are processed
return Promise.all(pendingOperations); // or await Promise.all(pendingOperations);
}
const addToDbServices = async () => {
await addImages();
...
}

Resources